Home > front end >  How to do two API calls in angular for same component
How to do two API calls in angular for same component

Time:02-06

How to make two different api calls for same angular component for example In a page I’m rendering order component twice in tabular manager using ngif condition to display different data.I have TAB1 & TAB2. In TAB1 API1 call happens right on page load .in Tab2 API2 call happens when clicked on the tab2 until then API2 call should not happen.

I want to happen it with single component don’t want create new component.

CodePudding user response:

you could create one component that takes an input and decides based on that <tab-component [initialApiCall]=false></tab-component>. Inside the components ngOninit() and click-handler you should wrap the api call in if(initialApiCall) apiCall();.

CodePudding user response:

First in ngOnInit. Second in selectedIndexChange catch function.

CodePudding user response:

Hi got your point you can handle both API calls with single component using two different functions I think you should try this : First API call will be done on page load then on click of TAB2 call a function containing second API call and on UI you can show loader & problem is solved.

But as a suggestion, you should call both the API's on page load & then on click of TAB1 or TAB2, you can show hide your data with ngIf directive.

Please let me know which solution works for you.

CodePudding user response:

For these kind of scenario go with reactive style of programing . Steps to do that 1) In your service file write the api call and return an observable of object. 2) While creating this make sure you use pipe and use rxjs operator sharereplay . 3) Create 2 variable of observable type ex input1$ = Observable and input2$ = Observable both will hold the response from api if required in any call you can do the same manupulation like mapping or filter etc. 4) In your html bind these observables with async pipe. you will get a benefits where the same api call is there you need not have to call it twice as the data remain same in the same component. go through this video it will be helpful for you https://www.youtube.com/watch?v=xGgwQvza0Ns&list=PLOa5YIicjJ-UqhGgX39GqN5Zc1itulsiH&index=1

  • Related