3

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?

0

5 Answers 5

8

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

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

getUser() {
    return this.afAuth.authState
}
4
  • makes sense. but, for the sake of the question.. how would I return an Observable Sep 12, 2017 at 4:58
  • 1
    I'm confused. isn't this.afAuth.authState returning an observable ?? Sep 12, 2017 at 5:01
  • if you want to change the return type of getUser function to observable then change it like getUser(): Observable<String> Sep 12, 2017 at 5:02
  • authState is an observable, yes.. but, suppose I want to consume it in there, and then return some other, new Observable Sep 12, 2017 at 5:04
3

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

2
  • You can also use Subjects...
    – P. Moloney
    Sep 12, 2017 at 9:43
  • 1
    create is deprecated, use new Observable() instead : getUser(): Observable<any> { return new Observable( (observer: Observer<string>) => { this.afAuth.authState.subscribe(user => { observer.next(user); }, (err) => observer.error("error")); }); } Nov 18, 2019 at 18:42
1

You need to set return type as observable

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.