Angular2:令牌刷新捕获401错误

Ale*_*lex 8 rxjs typescript angular

我是Angular2的新用户,尝试捕获401错误以进行令牌刷新,并计划重试原始请求...

这是我的authService.refresh方法:

refresh() : Observable<any> {
    console.log("refreshing token");
    this.accessToken = null;
    let params : string = 'refresh_token=' + this.refreshToken + '&grant_type=refresh_token';
    let headers = new Headers();
    headers.append('Authorization', 'Basic ' + this.clientCredentials);
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    return Observable.create(
        observer => {
            this._http.post('http://localhost:8080/oauth/token', params, {
                    headers : headers
            })
            .map(res => res.json()).subscribe(
                (data) => {
                    this.accessToken = data.access_token;
                    observer.next(this.accessToken);
                    observer.complete();
                },
                (error) => {
                    Observable.throw(error);
                }
            );
        });
 }
Run Code Online (Sandbox Code Playgroud)

然后我尝试在我的组件方法中使用刷新功能:

update(index : number) {
 let headers = new Headers();
 headers.append('Authorization', 'Bearer ' + this._authService.accessToken);
 this._http.get('http://localhost:8080/rest/resource', {
    headers : headers
 })
 .catch(initialError =>{
    if (initialError && initialError.status === 401) {
       this._authService.refresh().flatMap((data) => {
         if ( this._authService.accessToken != null) {
             // retry with new token
             headers = new Headers();
             headers.append('Authorization', 'Bearer ' +  this._authService.accessToken);
             return this._http.get('http://localhost:8080/rest/resource', { headers : headers });
         } else {
         return Observable.throw(initialError);
         }
       });
    } else {
      return Observable.throw(initialError);
    }
 })
 .map(res => res.json())
 .subscribe(
    data => {
      this.resources[index] = data;
    },
    error => {
      console.log("error="+JSON.stringify(error));
    }
 ); 
}
Run Code Online (Sandbox Code Playgroud)

由于某些原因这不起作用...我想知道angular2中令牌刷新功能的正确实现是什么?enter code here

Gün*_*uer 2

没有必要使用Observable.create(

        return this._http.post('http://localhost:8080/oauth/token', params, {
                headers : headers
        })
        .map(res => res.json())
        .map(data => {
                this.accessToken = data.access_token;
                observer.next(this.accessToken);
                observer.complete();
            },
        ).catch(error) => Observable.throw(error));
Run Code Online (Sandbox Code Playgroud)

只是不要调用.subscribe()(这将返回 aSubscription而不是 an Observable,而是使用.map(...)and.catch(...)