Reputation: 6649
Am new to angular2 and ionic2 and i would like to perform two requests after another successifull request
That is after a successifull login i would like to check if the returned token has access rights on the server an then redirrect the user accordingly
This is what i have tried but doesnt work
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())
}
}
This is the _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
});
}
Upvotes: 0
Views: 103
Reputation: 29625
checkAccessRights
returns an observable, you need to subscribe and check for true/false. Currently you are simply checking if an observable is returned.
Try:
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
});
});
}
With 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
});
}
Upvotes: 1