【发布时间】:2018-11-26 07:43:23
【问题描述】:
我有一个关于 observables 和订阅的问题。我正在开发一种方法,当我收到 http 401 状态时,会更新信号并更新函数,但这不起作用并且方法更新函数没有运行
这是带有订阅方式的函数:
ngOnInit() {
this.licenceList = new Array<License>();
this.subscription = this._phpService.tokenRefreshed$.subscribe(value =>{
if(value === true){
this._license.getLicenseList().subscribe(licenses => this.licenceList = licenses);
}
});
this._license.getLicenseList().subscribe(licenses => this.licenceList = licenses);
}
在这里我声明了 observable
private tokenRefreshed: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
tokenRefreshed$ = this.tokenRefreshed.asObservable();
用这个方法我刷新了令牌
interceptMex(message)
{
switch(message.status){
case 401:
++PhpService.tokenQueue;
if(PhpService.tokenQueue > 1 ){
return message.json();
}else{
this.refreshToken();
}
case 404:
return message.json();
default:
return message.json();
}
}
refreshToken(){
let url = "auth/refresh/self";
this.post(url, localStorage.getItem('refresh_token')).subscribe(res =>{
window.localStorage.setItem('access_token', res['access_token']);
window.localStorage.setItem('refresh_token', res['refresh_token']);
this.tokenRefreshed.next(true);
});
}
更新
发布功能:
post(url, parameters): Observable<any>
{
PhpService.layoutService.updatePreloaderState('active');
PhpService.loaderQueue++;
let apiDomain = this.config.settings.urlController;
let phpUrl = apiDomain + url;
let headers = new Headers({'Content-Type' : 'application/json'});
if(localStorage.getItem("access_token") != null){
headers.append('Authorization' ,localStorage.getItem('access_token'));
}
return this.http.post(phpUrl, '', {headers: headers, body: parameters})
.map(message => this.interceptMex(message))
.catch( error => Observable.of( this.interceptMex(error)))
.finally(() => PhpService.stopLoader());
}
有人可以帮我吗?
【问题讨论】:
-
好像根本没有调用
interceptMex方法?看起来 refreshToken 方法只将一个值传递给 tokenRefreshed observable -
@RudolfOlah 在 post 方法之后调用了 interceptMex 方法,我已经用 post 方法更新了代码
-
@RudolfOlah 检查我的更新
标签: angular typescript rxjs observable subscription