我有一个保存 token 的身份验证服务,保存 token 的结果是一个 promise 。我希望仅在 promise 解决后才将值返回到另一个函数。
这是我保存 token 的 authservice:
login(user: UserModel): Observable<any> {
return this._http.postnoAuth(this.loginurl + "mobile-login", body)
.map((response: Response) => {
let token = response.json() && response.json().access_token;
if (token){
this._storage.set('currentUser', JSON.stringify({token: token}))
.then(res=>{
return true; //return true after the promise is resolved
});
}
else{
return false;
}
})
//.catch(this.handleError);
}
那么我订阅上面的内容:
this._authservice.login(this.user).subscribe(respose => {
if(response){ //expecting true here
console.log("true");
}
else{
console.log("false");
}
loader.dismiss();
this.submitted = false;
},
error=> {
this.submitted = false;
}
);
即使设置了存储值,上面的代码也总是记录 false,可能是哪里出了问题?
最佳答案
我会尝试通过 flatMap
运算符来做到这一点。 flatMap
运算符帮助我们在前一个请求完成后调用一个请求:
return this._http.get('app/test.json')
.flatMap((response: Response) => {
let token = response.json() && response.json().access_token;
if (token) {
return this._storage.set('currentUser', JSON.stringify({ token: token }))
.then(res => {
return true;
});
} else {
return Observable.of(false);
}
});
不要忘记这些导入:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/observable/of';
<强> Plunker Example
关于javascript - 仅当 Angular2/ionic2 中的 Promise 得到解析时才执行 Observble,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42289512/