'angular 4 function return boolean = undefined
I can't seem to figure this out. I have a DataService (a.k.a. ds) and a component. The component calls a function doesUserExist():
console.log("boolean="+this.ds.doesUserExist());
This always comes up as undefined. Here's the function in DataService:
doesUserExist(){
var bool:boolean;
var myvars = this.af.list('/accounts/'+this.uid) as FirebaseListObservable<Listing[]>;
myvars.subscribe(data=>{
console.log("length="+data.length)
if (data.length===0){
bool = false;
}
})
return bool;
}
I tried putting the var bool:boolean as a public variable too, but no matter what happens, this comes as undefined.
I also set var bool:boolean=true and bool WILL equal false in the if statement above (I've checked via console.log) and instead of coming back as false it's still true per the designation above.
So what am I doing wrong with this? I've searched around and I tried:
Boolean([return bool]) but Code doesn't like that
I tried putting the returns in the if statement as well. That doesn't work.
Thank you!
Solution 1:[1]
You did not defined bool, and its not passing by your subscription (since its asynchronous, so answer might come later), so when you return bool, it has no value.
And since your function is based on the length of your response, you can remove that boolean.
doesUserExist(): Observable<boolean> {
var myvars = this.af.list('/accounts/'+this.uid) as FirebaseListObservable<Listing[]>;
return myvars.subscribe(data=>{
console.log("length="+data.length)
return data.length === 0; // true if that's the case, or false
})
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
