首页 > 解决方案 > 在拦截器中订阅时没有任何反应

问题描述

我想刷新一个令牌,但是当 api 调用完成时,令牌没有刷新,我看不到它里面的日志。在这里我设置了一个超时去快速测试刷新然后重试使用令牌请求但没有任何反应。它应该在到期前添加时间。

 if (token) {
      authReq = req.clone({
        headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token),
      });

      const jwtToken = JSON.parse(atob(token.split('.')[1]));

      const expires = new Date(jwtToken.exp * 1000);
      console.log(expires);

      const timeout = expires.getTime() - Date.now() - 100 * 1000;
      console.log('time', timeout);

      if (timeout >= 0 && timeout <= 19000) {
        
         this.http
          .post<any>(environment.apiBaseUrl + 'refresh', authReq.headers)
          .pipe(
            switchMap((d) => {
              //can't see its content
              console.log(d);
              authReq = req.clone({
                headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token),
              });
          console.log('after: ', expires);

              return next.handle(authReq);
            })
          );
      }
    }

如果我添加它,它会形成一个无限循环并且不会刷新。subscribe(); 在此处输入图像描述

标签: angularrxjsinterceptor

解决方案


您需要像这样返回http请求。

return this.http
          .post<any>(environment.apiBaseUrl + 'refresh', authReq.headers)
          .pipe(

这将导致请求触发。您的控制台日志根本没有触发的原因是没有触发 http 请求。

还使用map(). 你不需要一个switchMap()


推荐阅读