Lars
Lars

Reputation: 1092

How to create chained pipes to different observables?

I'm wondering how is it possible to call and process two different observables like this:

return this.restService.update('/events/' + data.ID, dbObj)
       .pipe(
        tap((response:any) => {
            console.error("1")
            this.restService.get('/data/' + userID + '/' + eventID)
                .pipe(
                    tap(response => console.log(response))
                );
            console.error("2")
        }))

this.restService is just a wrapper for http and it works. What's happen is that events is called fine and returns a result. Then console.log("1"), also the request to /data is send but now console.log("2") appears.

What I'm missing is the output of the "inner" console.log(response).

What I'm doing wrong?

Upvotes: 1

Views: 52

Answers (2)

Lars
Lars

Reputation: 1092

The service looks like this:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class RestService {
    constructor(private http: HttpClient) { }
    baseURL:string = 'http://wscm.localhost/rest';

    get(path: any): any {
        return this.http.get<any[]>(this.baseURL + path);
    }

    post(path: any, data: any): any {
        return this.http.post<any[]>(this.baseURL + path, data);
    }

    update(path: any, data: any): any {
        return this.http.put<any[]>(this.baseURL + path, data);
    }

    delete(path: any): any {
        return this.http.delete<any[]>(this.baseURL + path);
    }
}

Upvotes: -1

To get the response from the inner observable you might want to try the switchMap operator, so that the thing that you return is something like this

return this.restService.update('/events/' + data.ID, dbObj)
       .pipe(
        switchMap((response:any) => {
            console.error("1")
            return this.restService.get('/data/' + userID + '/' + eventID)
                .pipe(
                    tap(response => console.log(response))
                );
            console.error("2")
        }))

This way after the first observable this.restService.update(..) returns value, it will trigger the switchMap operator, that will replace the stream of this.restService.update with new one that is the response of this.restService.get(...)

Upvotes: 2

Related Questions