How to return an Observable in angular 4?

16.6k views Asked by At

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?

5

There are 5 answers

0
Suren Srapyan On BEST ANSWER

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;
   });
}
4
Sachila Ranawaka On

Don't subscribe inside the getUser function. Just return the obsevable.

getUser() {
    return this.afAuth.authState
}
0
Dheeraj Kumar On

You need to set return type as observable

getUser(): Observable<Type> {
    return this.afAuth.authState;
    });
}
0
Yonet On

You can return the function directly and subscribe to it in another class.

  getUser() {
        return this.afAuth.authState();
  }

You can think of observables as functions that are called by subscribing.

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

You can do something like this. Then in your component, the one which is calling this function, you can subscribe to this observable.

getUser(): Observable<any> {
    return Observable.create( (observer: Observer<string>) => {
     this.afAuth.authState.subscribe(user => {
        observer.next(user);
    }, (err) => observer.error("error"));
}); 
}

Ashley