无法从拦截器上的 Angular 中的BehaviorSubject 获取值,请参阅下文

问题描述 投票:0回答:1

common.service.ts

登录服务已创建。

export class CommonService {

  public tokenSubject: BehaviorSubject<UserToken>;
  public token: Observable<UserToken>;
  constructor(private httpclient: HttpClient,
              private router: Router
  ) { 
    this.tokenSubject = new BehaviorSubject<UserToken>(JSON.parse(localStorage.getItem('access_token') as string));
    this.token = this.tokenSubject.asObservable();
  }

  private commonApi = `${Appsettings._ApiEndpoint}`;

  login(data: any): Observable<any> {
    return this.httpclient.post<UserToken>(`${this.commonApi}api/user/user-login`, {loginData: data})
    .pipe(
      map(token => {
        const userToken: UserToken = token;

        localStorage.setItem('access_token' , JSON.stringify(userToken));
        this.tokenSubject.next(userToken);

        return userToken;
      })
    );
  }
}

 public get tokenValue(): UserToken {   
    return this.tokenSubject.value;
  }

用户.ts

export class UserToken {
    token: string;
}

登录.组件.ts

登录服务被调用,并传递请求的数据。

constructor(private commonservice: CommonService,
              private router: Router
  ) { }


 login(formData:NgForm, isValid: any) {
    if(isValid) {
      this.commonservice.login(formData.value)
      .subscribe((data: any) => {
        console.log('login data : ' , data);
        this.router.navigateByUrl('/dashboard');
      }, error => {
        console.log('error : ' , error);
        alert(error.error.message);
      })
    }
    
  }

我们在 tokenObj 和 isLoggedIn console.log() 中得到 null。这里有什么问题吗?还请帮助您更好、更深入地理解如何从角度中的BehaviorSubject RxJs 中获取价值。我们如何从BehaviorSubject获取数据?

请求拦截器.ts

我们无法在拦截器上获取令牌值。

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<any>> {
    
    this.spinner.show();
    
    const tokenObj = this.commonService.tokenValue;
    console.log('tokenObj : ' , tokenObj);
    const isLoggedIn = tokenObj && tokenObj.token;  
    console.log('isLoggedIn : ' , isLoggedIn);
    if(isLoggedIn) {   
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${tokenObj.token}`
        }
      })
    }
    return next.handle(request).pipe(
      tap(
        event => {
          if(event instanceof HttpResponse) {
            console.log('success in calling API : ', event);
            this.spinner.hide();
          }
        },
        error => {
          console.log('error in calling API : ', error);
          this.spinner.hide();
        }
      )
    );
  }

enter image description here

javascript reactjs angular
1个回答
0
投票

this.commonService.token.subscribe(tokenObj => {
  console.log('tokenObj:', tokenObj);
  const isLoggedIn = tokenObj && tokenObj.token;
  console.log('isLoggedIn:', isLoggedIn);

  if (isLoggedIn) {
    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${tokenObj.token}`
      }
    });
  }
  
  // Pass the modified request further
  return next.handle(request).pipe(
    tap(
      event => {
        if (event instanceof HttpResponse) {
          console.log('success in calling API : ', event);
          this.spinner.hide();
        }
      },
      error => {
        console.log('error in calling API : ', error);
        this.spinner.hide();
      }
    )
  );
});

© www.soinside.com 2019 - 2024. All rights reserved.