Handling multiple http responses one by one in Angular 6
Try this :
findOneByOne() {
const calls = this.getCardsPath().map(el => this.getPromises(el));
forkJoin(calls).subscribe(responses => {...});
}
responses
will contain every response, ranging from the first call to the last one : responses[0]
will be the response for the first element, and so on.
Best way for multiple HTTP Request in Angular
First of all, your code works and that's great - you can leave it as is and everything will be fine.
On the other hand, there is a way for multiple improvements that will help you and your colleagues in future:
- try to move http-related logic to the service instead of calling http in the components - this will help you to split the code into view-related logic and the business/fetching/transformation-related one.
- try to avoid nested
subscribe
s - not only you ignore the mighty power ofObservable
s but also tie the code to a certain flow without an ability to reuse these lines somewhere in the application. Returning theObservable
might help you with "sharing" the results of the request or transforming it in some way. flatMap/mergeMap
,concatMap
andswitchMap
work in a different way, providing you an ability to control the behaviour the way you want. Though, forhttp.get()
they work almost similar, it's a good idea to start learning those combining operators as soon as possible.- think about how you'll handle the errors in this case - what will happen if your first call will result an error?
Observable
s have a powerful mechanism of dealing with them, while.subscribe
allows you to handle an error only in one way.
An example using the switchMap
:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: 'app/app.component.html'
})
export class AppComponent {
loadedCharacter: {};
constructor(private http: HttpClient) {}
ngOnInit() {
const character$ = this.http.get('/api/people/1').pipe(
tap(character => this.characterWithoutHomeworld = character), // setting some "in-between" variable
switchMap(character => {
return this.http.get(character.homeworld).pipe(
map(homeworld => {
return {
...character,
homeworld: homeworld
}
}
)
)
}),
catchError(errorForFirstOrSecondCall => {
console.error('An error occurred: ', errorForFirstOrSecondCall);
// if you want to handle this error and return some empty data use:
// return of({});
// otherwise:
throw new Error('Error: ' + errorForFirstOrSecondCall.message);
})
);
// you can either store this variable as `this.character$` or immediately subscribe to it like:
character$.subscribe(loadedCharacter => {
this.loadedCharacter = loadedCharacter;
}, errorForFirstOrSecondCall => {
console.error('An error occurred: ', errorForFirstOrSecondCall);
})
}
}
Angular wait for multiple http requests to complete and then fire the last one
You should use forkJoin
to achieve the desired result. forkJoin
waits for all obesrvables to complete before emitting a value. Example:
forkJoin(
this.data.getCodes('medical'),
this.data.getCodes('delay'),
this.data.getCodes('disability'),
this.data.getCodes('district'),
).subscribe(([medicalData, delayData, disabilityData, districtData]) => {
this.Medical = medicalData;
this.Delays = delayData;
this.Disability = disabilityData;
this.District = districtData;
// make your last http request here.
});
Is it possible to combine 2 http responses into one in Angular?
You need to use forkJoin of rxjs
import { forkJoin } from "rxjs/observable/forkJoin"; // Maybe import from 'rxjs' directly (based on the version)
...
public multipleRequestMethod() {
const firstCall = this.http.get('www.example.com/records/?count=50');
const secondCall = this.http.get('www.example.com/records/?count=50&lastID=FAKEID');
return forkJoin(firstCall, secondCall).pipe(
map([firstResponse, secondResponse] => [...firstResponse, ...secondResponse])
)
}
More info: Here
If you want to use response from first request then you need to use flatMap/switchMap
import { map, flatMap } from 'rxjs/operators';
...
public multipleRequestMethod() {
return this.http.get('www.example.com/records/?count=50').pipe(
flatMap(firstResult => {
return this.http.get('www.example.com/records/?count=50&lastID=' + firstResult[firstResult.length - 1].id).pipe(
map(secondResult => [firstResult, secondResult])
);
})
);
}
Multiple Http calls in one array
The best way would be to call one endpoint with necessary data but this requires change on backend.
If change on backend is not an option and You have no middleware to support UI it depends on what You need in this case but from what you've described it seems that forkJoin, combineLatest or withLatestFrom is what You should use if calls are independent, if You need to have output of previous calls to call next ones You can use flatMap or switchMap. It's hard to say without looking at code but I think that some of mentioned operators should do the trick.
How to call multiple http requests parallel and handle errors individually
You need to combine all observables from your service into a single observable and then subscribe to the newly created observable. to do this you can use RxJs operator forkJoin
the fork join subscription will wait for all observables to complete and then emit the values to the subscription method -note that mean single success and single error for all since the observable will only emit once
you can also use RxJs Operator combineLatest
this will create single observable from your list of observers and emit a value every time one of the observables complete. the value will be array of all last values emmited from your observers or null in case an observer not finished. this will allow you to handle error state for each api call but will also fire the subscription event multiple times.
Related Topics
Checking for Null Is Not Working for Ajax Json Data
How to Add a New Object (Key-Value Pair) to an Array in JavaScript
Open Html5 Date Picker on Icon Click
Ngx-Datatable Set Column Width Dynamically
How to Extract the User Name from an Email Address Using JavaScript
Select Li Element With Arrow Keys (Up and Down) Using JavaScript (Jquery)
How to Pass Id from Modal in Boostrap to PHP File
Javascript File Not Updating No Matter What I Do
Calculate Time Difference Between Two Date in Hh:Mm:Ss JavaScript
Input Field Value Should Not Be Greater Than Other Field Value
How to Change Text Value Upon Button Press in React Native
Allow Negative/Positive Numbers But Not Letters
Filtering Multiple Items With Es6 Array Functions
Retaining the Textbox Values Even After Refresh
The Use of the Triple Exclamation Mark
How to Insert Dashes Between Each Two Even Digits of a Specific Number