0

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);
});
6
  • 1
    Either you move your code inside the subscribe or you convert the observable (getOrderList) and await it instead of a subscription. Commented Jul 4, 2022 at 19:23
  • Additional information: the subscription is async and the code below is processed directly. this is way you need "special" strategies to handle your case. Commented Jul 4, 2022 at 19:25
  • I tried adding inside subscribe but it is not working as expected Commented Jul 4, 2022 at 19:31
  • What is your expectation? (i guess in this case more details needed) Commented Jul 4, 2022 at 19:34
  • Can you suggest me any example for await? Commented Jul 4, 2022 at 19:42

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.