Patrioticcow
Patrioticcow

Reputation: 27048

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?

Upvotes: 3

Views: 16688

Answers (5)

ashley
ashley

Reputation: 1038

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

Upvotes: 3

Suren Srapyan
Suren Srapyan

Reputation: 68665

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

Upvotes: 8

Yonet
Yonet

Reputation: 106

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

Upvotes: 0

Dheeraj Kumar
Dheeraj Kumar

Reputation: 4175

You need to set return type as observable

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

Upvotes: 1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41437

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

getUser() {
    return this.afAuth.authState
}

Upvotes: 3

Related Questions