1

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!

Groovdafied
  • 45
  • 1
  • 1
  • 8
  • 1
    Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – n00dl3 Sep 20 '17 at 08:14

1 Answers1

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
    })
  }
Quentin Laillé
  • 125
  • 1
  • 12
  • I don't see that `doesUserExist` function returns something – yurzui Sep 20 '17 at 08:01
  • Ya, that's what I did too, setting boolean to true, but would return as true regardless if the IF statement changes it to false. You mentioned that the data is asynchronous; are you saying that the site may need a few seconds for this to all work properly? Or better put (after thinking of my answer), that function is being requested and acted upon in the component before it got the response from the dataService? – Groovdafied Sep 20 '17 at 08:03
  • I just re-edited your code, not I'm my cup this morning, but since its bind to a request and thus async, make sure when using this method that everything before is related to an Observable (variables, pipe async,...) – Quentin Laillé Sep 20 '17 at 08:11