我正在我的angular 2应用程序中实现刷新令牌,这是我的代码。我的刷新令牌后调用没有被调用。我在调用刷新令牌时也没有看到任何错误,以找到问题。感谢帮助
refreshToken(): Observable<any> {
console.log("refreshing token");
let body: string = 'grant_type=refresh_token&refresh_token=' + localStorage.getItem("refresh_token");
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
return Observable.create(
(observer: Observer<any>) => {
this.http.post('https://fedqa.test.com/as/token.oauth2', body, options)
.map(res => res.json()).subscribe(
(data) => {
localStorage.removeItem("access_token");
localStorage.removeItem("refresh_token");
localStorage.setItem("access_token", data.access_token);
localStorage.setItem("refresh_token", data.refresh_token);
localStorage.setItem("token_type", data.token_type);
localStorage.setItem("expires_in", data.expires_in);
},
(error) => {
Observable.throw(error);
}
);
});
}
这是我的API调用,我检查401并执行refreshToken()函数,并在获得新的访问令牌后调用相同的函数。
getInspections(statusesinput: string[]): Observable<IInspection[]> {
let body = JSON.stringify({ "Statuses": statusesinput });
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Authorization', 'Bearer' + localStorage.getItem("access_token"));
headers.append('Access-Control-Allow-Origin', '*');
let options = new RequestOptions({ headers: headers });
return this.http.post(this._baseUrl + '/Inspections/ListInspections', body, options)
.map((res: Response) => {
this.inspections = res.json();
return this.inspections;
})
.catch(initialError => {
if (initialError && initialError.status === 401) {
this.refreshToken().flatMap((data) => {
if (localStorage.getItem("access_token") != null) {
// retry with new token
return this.getInspections(statusesinput);
} else {
return Observable.throw(initialError);
}
});
} else {
return Observable.throw(initialError);
}
})
}
答案 0 :(得分:3)
尝试添加评论,但还没有权利..
您可以在此处找到您的问题 - Angular2: Catching 401 error for token refresh
尝试从refreshToken()
方法中删除订阅。并在this.refreshToken().flatMap((data) => {
。