当api响应状态为角度2的401时,如何实现Interceptor刷新令牌

时间:2016-09-20 08:22:39

标签: angular

是Angualr 2的新手,当api响应为非授权(401)错误时,在刷新令牌时遇到问题。什么想通过使用拦截器来实现这个概念。请提出任何意见或建议。

3 个答案:

答案 0 :(得分:0)

在角度2中,我们没有拦截器的概念,我们可以通过创建扩展标准http服务的自定义http服务来实现。在您的应用程序模块中,您可以指向angular以在需要http服务的任何地方使用自定义http服务。

答案 1 :(得分:0)

以下代码将有助于实现刷新令牌Intercepter  `get(url:string):Observable {

    let headers = new Headers({'Content-Type': 'application/json', 'Authorization': 'bearer ' + this.token});
    return this._http.get(url, {headers: headers})
        .map((res: Response) => {
            return res;
        })
        .catch(error=> {
            if (error.status === 401) {
                return this.RefreshToken().flatMap((newToken) => {
                    let newheaders = new Headers({
                        'Content-Type': 'text/plain',
                        'Authorization': 'bearer ' + this.token
                    });
                    return this._http.request(url, {headers: newheaders});
                })
            } else {
                return Observable.throw(error);
            }
        });
} `

答案 2 :(得分:0)

你可以更好地处理订阅中的401 unathorized,下面是代码,你可以在组件本身使用它

this.dynamic.getProfileDetails(this.userId, this.password).subscribe(
      v => (this.firstName = v.firstName),
      (err) => {
        // check if it is 401 and the token is invalid
        if (err.status == 401 && err.json().oauth2ErrorCode=='invalid_token') {
          console.log("Error Description " + err.json().oauth2ErrorCode);
          console.log("inside component error");
          //  refresh the token
          console.log("refresh the token")
          this._getNewToken.getNewTokenService().subscribe(
            v => {
              //  token is refreshed so retry the original request
              console.log("retry the original request with the new acces token")
              this.dynamic.getProfileDetails(this.userId, this.password).subscribe(
                v => (this.firstName = v.firstName)
              )
            },
            (refreshErr) => {
              if(refreshErr.status == 401 && refreshErr.json().oauth2ErrorCode=='invalid_token')
              {
                console.log("refresh token 401"+refreshErr.json().oauth2ErrorCode);
                this._router.navigate(['login']);
              }
              else if(refreshErr.status==400)
              {
                console.log("inside 400 "+refreshErr );
                this._router.navigate(['login']);
              }
              else
              {
                console.log("error des "+refreshErr );
                this._router.navigate(['login']);
              }
            }
          );



        }
        else{
               //serve  error logout from the app
                this._router.navigate(['login']);
               console.log("server error");
        }
      }
    );