4

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});
   })
}
Nazar Kalytiuk
  • 1,499
  • 1
  • 11
  • 21

3 Answers3

2

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.

qaisjp
  • 722
  • 8
  • 31
1

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

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 ?