Search code examples
angularfirebaseasynchronousangularfire

How to wait for async subscribe to full fill a global variable?


I have an async firebase call similar to:

this.fbProvider.fbGetProfile()
               .subscribe(p => {                                       
                            this.profile = p;
                         });

...but then I need to use this.profile in others function like...

console.log(this.profile.email);

...and it keeps returning an error:

Cannot read property 'email' of undefined

any idea how I could wait for the subscribe to full fill my local variable before I need to use it?

ps: my problem is bigger than that and solutions such as using .then() makes my code a mess. I tried something with await, but it did not work out as well.

`


Solution

  • You can use async / await with promise and resolve that once the api call completes:

    await new Promise(resolve => {
        this.fbProvider.fbGetProfile()
               .subscribe(p => {                                       
                            this.profile = p;
                            resolve();
                         });
    });
    

    Remember to put async before the function where you use this code.