Angular2 - How to chain async service calls (http requests) in a component?

前端 未结 5 2111
刺人心
刺人心 2020-12-17 18:59

I have a component which first need to call a service that POST something. Then in the same component I want to wait until the POST is done, to call another service which

5条回答
  •  [愿得一人]
    2020-12-17 19:50

    When a call returns a Promise chain the calls with

    someFunction() {
      return returnsPromise()
        .then(result => doSomethingNext())
        .then(result => doSomethingAfterThat());
    }
    

    Ensure you have a return that returns the Promise of that chain so the caller of someFunc() also has a chance to time additional work to execute after doSomethingAfterThat() is completed.

    When a call returns an Observable then use the complete callback

    someFunction() {
      return returnsObservable()
        .subscribe(
          event => doForEachEvent(),
          error => handleError(),
          () => doSomethingNext()
              .then(result => doSomethingAfterThat());
    }
    

    doSomethingNext() is executed after the last event and doSomethingAfterThat() is again chained with then() to show how to mix observable and promise. doSomething().

提交回复
热议问题