Search code examples
angularobservableangular2-observables

Returning when multiple observables have finished - Angular2


I am trying to chain two actions that need to be performed right after each other as follows:

public main(data) {

    // A. 
    return this.methodA(data)
    .map(resA => {
      if (resA.hasOwnProperty('id')) {

        console.log('gets triggered');

        // B. 
        return this.methodB(resA).map(resB => {

          console.log('does not get triggered', resB)
          return resB.json();
        })

      } else {
        return resA;
      }
    })

}

Problem is that the second method does not get triggered. It only returns to me the observable and not the result from the observable (resB). How can this be overcome?

I am happy to do it also with promises, but I am not sure how that would work?


Solution

  • You can do this.

    public main(data) {
    
        return Observable.create(observer => {
            this.methodA(data).subscribe(resA => {
                if (resA.hasOwnProperty('id')) {
                    this.methodB(resA).subscribe(resB =>{
                        observer.next(resB);
                    })
                } else {
                    observer.next(resA);
                }
            }
        });
    
    }
    

    And then you have to subscribe on method main