1
我正在使用angular2和ionic 2s框架存儲。我打了幾個電話給我的API,在他們面前我打電話refresh()
函數刷新令牌,如果需要的話。Token在HTTP請求之前刷新,但新的令牌未與請求一起發送
問題的一個示例:用戶在搜索欄中開始鍵入「AB」並且令牌過期。用戶現在鍵入「C」,refresh()
被調用,但不會與請求一起發送令牌,但如果用戶在提供令牌後立即按下「D」,則我的猜測是在令牌之後正在調用API從存儲已經被刪除,但它被保存
get(): Promise<any> {
return this.storage.get('token_id').then(token_id => {
this.token_id = token_id;
});
}
set(token_id) {
this.storage.set('token_id', token_id);
}
refresh(): Observable <any> {
let obs = Observable.fromPromise(this.get())
.filter(() => this.jwtHelper.isTokenExpired(this.token_id))
.flatMap(() => this.authHttp.get('http://api.app/api/refresh?token_id=' + this.token_id));
obs.subscribe((response: Response) => {
this.token_id = response.json().token_id;
this.set(this.token_id);
}, (error: Response) => {
console.log(error);
});
return obs;
}
服務,使調用刷新訂閱了搜索()調用
search(key): Observable<any> {
this.userService.refresh();
return this.authHttp.get('http://' + keyword)
.map(
(response: Response) => {
return response.json();
},
(error: Error) => {
console.log(error);
}
);
}
組件之前,()調用
onSearch(event)
{
let key = event.target.value;
this.searchService.search(key)
.subscribe(
(prods: SearchInterface[]) => this.prods = prods,
(error: Response) => {
}
);
}
當如果令牌到期,則服務器將用401或403錯誤代碼響應搜索API調用獲得令牌。因此,如果您在調用刷新令牌後在搜索api調用上收到該錯誤,則只需再次調用相同的搜索API即可。 – SAJ