我是angular2和ionic2的新手,我想在另一个成功请求之后执行两个请求
那就是在成功登录后,我想检查返回的令牌是否在服务器上具有访问权限,然后相应地重新引导用户
这是我尝试过的但不起作用
redirrect(token: string) {
//console.log(token) returns value of the token
if (this._authservice.checkAccessRights(token, "is-marshal")) {
this._navCtrl.setRoot(MarshalPage);
} else if(this._authservice.checkAccessRights(token, "can-read")) {
this._navCtrl.setRoot(UserPage);
} else {
//force logout then redirrect to login page
return this._authservice.logout()
.subscribe(() => {
this.showtoast("No access rights");
this._navCtrl.setRoot(LoginPage);
},
error=>this.handleError())
}
}
这是_authservice
checkAccessRights(usertoken: string, permission: string): Observable<any>
{
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + usertoken);
return this._http.post(this.authurl +"can-access",permission)
.map((response: Response) => {
return response; //this response is true or false from server
});
}
checkAccessRights
返回一个可观察值,则需要订阅并检查是否为真。当前,您只是在检查是否返回了一个observable。
尝试:
redirrect(token: string) {
//console.log(token) returns value of the token
this._authservice.checkAccessRights(token, "is-marshal").subscribe(
data=>{
data?
this._navCtrl.setRoot(MarshalPage):
this._authservice.checkAccessRights(token, "can-read").
subscribe(data=>{
if(data)
this._navCtrl.setRoot(UserPage);
else
this._authservice.logout()
.subscribe(() => {
this.showtoast("No access rights");
this._navCtrl.setRoot(LoginPage);
},
error=>this.handleError());
//force logout then redirrect to login page
});
});
}
使用switchmap:
redirrect(token: string) {
canRead$ = this._authservice.checkAccessRights(token, "can-read").switchmap(data=>data?Observable.fromPromise(this._navCtrl.setRoot(UserPage)).mapTo(true)):
this._authservice.logout().mapTo(false));
marshal$ = this._authservice.checkAccessRights(token, "is-marshal").switchmap(data=>{data? Observable.fromPromise(this._navCtrl.setRoot(MarshalPage)).mapTo(true):
canRead$);
marshal$.subscribe(data=>{
if(!data){
this.showtoast("No access rights");
this._navCtrl.setRoot(LoginPage);
},
error=>this.handleError());
//force logout then redirrect to login page
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句