使用subscribe异步方法刷新令牌

时间:2018-04-21 16:49:08

标签: angular

我在AuthService中有刷新方法:

refresh() {
          const body = new HttpParams()
                .set('grant_type', 'refresh_token')
                .set('refresh_token', this.storage.getRefreshToken());
            let headers = new HttpHeaders();
            headers = headers.append("Authorization", "Basic " + btoa("my-client:secret"));
            headers = headers.append("Content-Type", "application/x-www-form-urlencoded");
            return this.http.post('http://localhost:8090/oauth/token', body.toString(), {
                headers: headers});
      }

当我转到应用程序页面时,我想要access_token刷新。我在我的应用程序中添加了INTERCEPTOR:

intercept(req: HttpRequest<any>, next: HttpHandler) {
        if (req.url.includes('/users')) {
            this.auth.refresh().subscribe(
               (data:any) => {this.storage.setToken(data.access_token,
               data.refresh_token); });
            req = req.clone(
                {
                    setHeaders: {
                        Authorization: `bearer ${this.storage.getAccessToken()}`
                    }
                }
            );
        }
        return next.handle(req);
    }

存储 - 服务,使用localStorage。

我不知道如何处理来自服务器的响应。我理解订阅异步方法,但我不明白我需要做些什么来使这项工作。

1 个答案:

答案 0 :(得分:0)

使用flatMap尝试这个

 intercept(req: HttpRequest<any>, next: HttpHandler) {
    if (req.url.includes('/users')) {
        return this.auth.refresh().flatMap((data:any) => {
           this.storage.setToken(data.access_token,data.refresh_token);
           newReq = req.clone(
            {
                setHeaders: {
                    Authorization: `bearer ${this.storage.getAccessToken()}`
                }
            }
          );
           return next.handle(newReq);
        }); 
       } 
    }