【发布时间】:2020-04-03 11:39:55
【问题描述】:
我有一个函数应该返回一个布尔值,基于发出 http post 请求的函数的返回值:
checkPost(callRequest: boolean): boolean {
console.log('START REQUEST');
if(callRequest){
this.makeRequest().subscribe(result => {
console.log(`RESULT ${result}`);
return result;
}
console.log('THIS SHOULD NEVER SHOW');
}else{
...
}
console.log('THIS SHOULD ALSO NEVER SHOW');
}
makeRequest 相当简单:
makeRequest(): Observable<boolean> {
...other stuff...
return this.http.post<UserData>(oauth2_token_endpoint, body, {headers})
.pipe(map(user => {
if (user && user.access_token) {
this._saveToken(user);
this.currentUserSubject.next(user);
return true;
}
return false;
}));
}
帖子可能需要 1-5 秒,这很好,但我想确保 checkPost() 返回 makeRequest() 的结果(等待它)。永远不可能超越if / else,正确的方法是什么?
我试过了:
this.makeRequest().pipe(map(result => {
console.log(`RESULT: ${result}`);
return result;
}));
但这毕竟不会触发请求。
Angular 8.2.14
【问题讨论】:
标签: angular observable