对于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
});
}
答案 0 :(得分:1)
checkAccessRights
返回一个observable,你需要订阅并检查是否为true / false。目前,您只是检查是否返回了一个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
});
}