首页 > 解决方案 > 在角度 8 的自定义方法中调用拦截

问题描述

在 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))
    );
  }

标签: javascriptangularrxjsintercept

解决方案


推荐阅读