Nazar Kalytiuk
Nazar Kalytiuk

Reputation: 1759

How to return observable from subscribe?

For example, I have code like this:

// angular service post method
postUser(): Observable<User> {
   this.tokenService.getToken().subscribe(token => {
       // need to return this observable
       return this.http.post<User>(url, {token});
   })
}

Upvotes: 4

Views: 4171

Answers (3)

qaisjp
qaisjp

Reputation: 811

If you do this, the return type is Observable<Observable<User>>, not nice:

  getUser(): Observable<Observable<User>> {
    return this.accessToken$.pipe(
      map(_ => {
        return this.http.get<User>(`${environment.apiURL}/user`)
      }),
    );
  }

Use mergeMap:

 getUser(): Observable<User> {
    return this.accessToken$.pipe(
      mergeMap(_ => {
        return this.http.get<User>(`${environment.apiURL}/user`)
      }),
    );
  }

Refer to "Flattening nested Observables" for more information.

Upvotes: 2

olivier cherrier
olivier cherrier

Reputation: 274

Here an example of code

  save(person: Person) : Observable<Response>{
    return this
      .http
      .put(`${this.baseUrl}/people/${person.id}`,
            JSON.stringify(person),
            {headers: this.getHeaders()});
  }

See here for more details.

And use switchMap to manage nested Observables.

Your post should update the database. Why no user is in parameter of your method ?

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658037

You can't, But you can easily avoid subscribe and instead use map, or do

postUser(): Observable<User> {
   return this.tokenService.getToken().map(token => {
       // need to return this observable
       return this.http.post<User>(url, {token});
   })
}

you might want to have a look at mergeMap and other available operators as well for your use case. See also https://www.learnrxjs.io/operators/transformation/mergemap.html

Upvotes: 1

Related Questions