Search code examples
angulartypescriptobservablesubscriber

How to return an Observable in angular 4?


I have this method inside a authProvider provider class:

getUser() {
    return this.afAuth.authState.subscribe(user => {
        return user;
    });
}

I would like to subscribe to it in a different class, something like:

this.authProvider.getUser().subscribe(user => console.log(user));

any ideas how to return an Observable inside the getUser() method?


Solution

  • Your authState is already Observable. Just return your authState and subscribe within another function. In the function for any other work you can use RxJS#map function.

    getUser() : Observable {
        return this.afAuth.authState.map(...);
    }
    
    ....
    
    login() {
       getUser().subscribe(user => {
           return user;
       });
    }