How to return an Observable in angular 4?

Patrioticcow picture Patrioticcow · Sep 12, 2017 · Viewed 16.4k times · Source

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?

Answer

Suren Srapyan picture Suren Srapyan · Sep 12, 2017

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;
   });
}