Steve
Steve

Reputation: 149

Angular 2 - Two Services, second requires result of first

I guess I need some type of promise chain, but the syntax eludes me...

Within the same component:

I'm calling:

this.somethingService.getSomethings().then(somethings => this.somethings = somethings);

Then I need to call:

this.otherService.getOthers(this.somethings).then(others => this.others = others);

In the second service call I'm using the result of the first to perform aggregate functions on its content, but its empty when the second call is made, thus the second service returns empty.

How can I get the second service to wait until the first promise has been resolved.

Thanx

Steve

Upvotes: 1

Views: 108

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202256

You can chain promises this way:

this.somethingService.getSomethings().then(somethings => {
  this.somethings = somethings;
  return this.otherService.getOthers(somethings);
}).then(others => {
  this.others = others;
});

The second callback will receive the result of the promise returns by the first callback.

Upvotes: 1

Related Questions