我想返回一个布尔值,但是“if”条件中的变量是未定义的。
function() {
this.menuDataService.getMenu()
.subscribe(res => {
this.mainMenus = res.MainMenus;
console.log(this.mainMenus);
});
console.log(this.mainMenus);
if(this.mainMenus == 1){
return true;
}
else {
return false;
}
}
答案 0 :(得分:3)
一旦开始使用observable,就必须在observable的链式方法集中工作。在你的情况下,你可以做这样的事情:
function InnerFunc(){
return this.menuDataService.getMenu()
.map(res => {
if(res.mainMenus == 1){
return true;
}
else{
return false;
}
)
}
function OuterFunc() {
InnerFunc()
.subscribe(result =>{
// will be either true or false
console.log(result);
});
}
答案 1 :(得分:2)
seecode的回答对我有所帮助,但我无法发表评论。
我只是想说,使用RxJS 6,他们改变链接Observable运算符的方式,现在我们必须使用pipe(...)方法。 (见RxJS 6 - What Changed? What's New?)
以下是他的InnerFunc看起来更新为RxJS 6:
function InnerFunc(){
return this.menuDataService.getMenu().pipe(
map(res => {
if(res.mainMenus == 1){
return true;
}
else{
return false;
}
)
)
}
答案 2 :(得分:1)
您最终可以获得observable
以上的事件,以便subscription
被调用。
this.menuDataService.getMenu()
.finally( () => { console.log(this.mainMenus) });
.subscribe(res =>{
this.mainMenus = res.MainMenus;
console.log(this.mainMenus);
});