我正在尝试使用 rxJS 来处理来自 angular2 中 http 请求的响应
这是代码:
isUserConfirmed(): boolean {
let result: boolean = false;
this.authService.isUserConfirmed().subscribe(
retrievedData => {
//if no errors from the server
if (retrievedData.success) {
//if the confirmed flag is true
if (retrievedData.payload){
result = true;
console.log("i"+result);
} else {
result = false;
}
} else {
this.showError(retrievedData.message);
}
},
error => {
this.showError(error);
});
console.log("o"+result);
return result;
},
showError(error) {
//...
}
编辑
当我运行这个时,我得到这个输出:
ofalse
itrue
这意味着结果值在 suscribe 方法中设置为 true,但这不会更改返回的结果值。
如何设法从订阅块内部返回设置的值?
这是因为订阅块之外的控制台语句将首先执行。所以你的第一个控制台.log(( 将显示 false。跟随你的控制台.log(( 在订阅块内将执行第二个。因此,如果成功,结果将是真的。
如果 Observable 返回 true,则结果应为 :
false
true
你可以通过这种方式返回值
isUserConfirmed(): boolean {
let result: boolean = false;
return this.authService.isUserConfirmed().subscribe(
retrievedData => {
//if no errors from the server
if (retrievedData.success) {
//if the confirmed flag is true
if (retrievedData.payload){
result = true;
console.log("i"+result);
}
} else {
this.showError(retrievedData.message);
}
return result
},
error => {
this.showError(error);
});
}