I'm studying the Observables in Angular2/4, before I've used the Promises for my services call.
I'm wondering what is the best way to make multiple sync calls. Let me explain with an example: my app component have a getUserInfo() method that need to make 3 calls to 3 different services that depends on each other.
getUserId():Number // return the logged in user userId from the session
getUserPermissions(userId):Array<String> // return a list of permission from the userId
getUserInfo(userId):String // return some additional info for the user
Now let suppose that I have an User object as the following:
export class User {
id: number;
name: string;
info: string;
permissions: array<string>;
}
I need to create a new instance of User class with the results of the 3 services call, so I need to run:
- getUserId();
- getUserPermissions();
- getUserInfo();
What is the best and most polite way to accomplish this through Observable?
With promises I would have something like this:
this._service.getUserId().then(r1 => {
let userId: number = r1;
this._service.getUserPermissions(userId).then(r2 => {
let userPermissions: Array<String> = r2;
this._service.getUserInfo(userId).then(r3 => {
let userInfo: string = r3;
let user: User = new User(userId, userInfo, userPermissions);
});
})
});
I can't guarantee that this is the best or most polite way because RxJs is such a powerful library where you can achieve the same result in many different ways, but I'll give it a shot.
I will chip in two options.
Assuming your service looks something like this:
userservice.ts
Notice that the methods return Observables of JSON-objects!
Since Angular http already returns Observables, it is probably the easiest and cleanest to keep it an Observable-chain all the way down.
Of course you could use the
map
-operator (f.e..map(result => result.info)
) inside of the service method to make the return type toObservable<string>
instead ofObservable<{ info: string }>
.switchMap
This approach is suited for requests that have to happen in a specific order.
If you open the network-tab of your browser you will see that the requests are executed in sequence, meaning that each request has to finish before the next one starts. So
getUserId()
has to finish beforegetUserPermission()
starts, which in turn has to finish beforegetUserInfo()
can run... and so on.You can also use
mergeMap
instead. The only difference is, that switchMap can cancel an ongoing http-request when a new value is emitted by the source observable. Look here for a good comparison.forkJoin
This approach allows you to execute requests in parallel.
Since
forkJoin
runs all the Observable sequences it has been given in parallel, it is the better option if the requests (or at least some of them) don't depend on each other.In this example, the
getUserId()
-request will run first, and once it has finished bothgetUserPermission()
andgetUserInfo()
will start running in parallel.Both methods will return an object with the following structure: