在 Angular 8 的自定义方法中调用拦截

时间:2020-12-22 14:00:31

标签: javascript angular rxjs intercept

在 signInWithToken 方法中,我得到一个令牌,需要在请求标头中将其设置为“授权”,Bearer ${token for here}。但是问题是调用signInWithToken方法的时候会发生重定向,intercept()方法来不及调用。如何强制在signInWithToken()方法内部调用intercept()方法?它们都在同一个服务中。

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (this.access) {
      req = req.clone({
        headers: req.headers.set('Authorization', `Bearer ${this.access}`)
      });
    }
    
    ...  // standard code for intercept
    
  }

  signInWithToken(login: string, password: string): Observable<any> {
    return this.http.post('./api/internal/auth/sign-in-with-token', {login, password}).pipe(
      map((details: SignInDetails) => {
        this.areCookiesValid = true;
        this.access = details.token; // in this method, when we received the token, we need to call intercept

        return details;
      }),
      catchError((error) => throwError(error))
    );
  }

0 个答案:

没有答案
相关问题