Subathra
Subathra

Reputation: 13

Code is running before API call response in typescript

Before my API response below code is getting running. I want to get a response from the API call based on the API response I want to proceed further

 this._httpservice.getOrderList().subscribe((response: any) => {
  Object.entries(response.content).forEach(([key, value]) => {
    this.orderList.set(key, value as Array<String>);   //Set Value in Map
  });
}, error => {
  this.errorDetails = error;
});

//Based on the Map value I want to push values in an array

this.orderList.get(this.orderName).map(value => {
  this.availableOrders.push(value);
});

Upvotes: 0

Views: 230

Answers (1)

JSmart523
JSmart523

Reputation: 2497

As a rule of thumb, do not subscribe to something that is set via subscription, and do not subscribe within a subscribe. Both are strong indicators there's a better way.

In your case, it sounds like you want availableOrders to be updated as appropriate. Have you considered making availableOrders an observable?

For example:

type OrderList = Record<string, Array[string]>;


const orderList: OrderList = {};

const orderList$ = this._httpservice.getOrderList().pipe(
  map(({content}) => Object.assign(this.orderList, content)),
  shareReplay(1) // not needed if you only have one downstream subscriber
);

const orderName$: Subject<string> = new Subject(); // no idea how you populate this in your app. Maybe FormControl.ValueChanges?

const availableOrders$ = this.orderName$.pipe(
  combineLatestWith(this.orderList$),
  map(([nm, orderList]) => orderList[nm])
);

No subscriptions you need to clean up. And then in your template you can replace availableOrders with availableOrders$ | async.

Upvotes: 1

Related Questions