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:
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);
});
})
});
Add the following code inside the app.component.html file. Save the file and start the angular development server. Go to the http://localhost:4200 and see the result after 1 second. So, we have successfully got the data using Observables. Remember, Observables producing the values Asynchronously.
Fetching numerous asynchronous requests and managing them can be tricky but with the Angular's Http service and a little help from the included RxJS library, it can be accomplished in just a few of lines of code. There are multiple ways to handle multiple requests; they can be sequential or in parallel. In this post, we will cover both.
The Async pipe will allow us to let angular know what properties on our component are Observables so it can automatically subscribe and unsubscribe to our component for us. Let's take a look at the component.
The content is likely still applicable for all Angular 2 + versions. Angular applications heavily rely on RxJS Observables. While building large front end apps with these technologies we quickly will need to learn how to manage subscribing to multiple Observables in our components.
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
@Injectable()
export class UserService {
constructor(private http: Http) { }
getUserId(): Observable<{ id: number, name: string }> {
return Observable.of({ id: 3, name: 'Bob' }).delay(300);
/*
* replace with http:
* return this.http.get('http://my.api.com/api/user/id').map(res => res.json());
*/
}
getUserPermission(userId: number): Observable<{ permissions: string[] }> {
return Observable.of({ permissions: ['user', 'admin'] }).delay(300);
/* return this.http.get(`http://my.api.com/api/user/${userId}/permissions`).map(res => res.json()); */
}
getUserInfo(userId: number): Observable<{ info: string }> {
return Observable.of({ info: 'is a nice person'}).delay(300);
/* return this.http.get(`http://my.api.com/api/user/${userId}/info`).map(res => res.json()); */
}
}
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 to Observable<string>
instead of Observable<{ info: string }>
.
This approach is suited for requests that have to happen in a specific order.
this.userService.getUserId()
.switchMap(userResult =>
this.userService.getUserPermission(userResult.id)
.switchMap(permissionsResult =>
this.userService.getUserInfo(userResult.id)
.map(infoResult => ({
id: userResult.id,
name: userResult.name,
permissions: permissionsResult.permissions,
info: infoResult.info
}))
)
)
.subscribe(v => console.log('switchmap:', v));
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 before getUserPermission()
starts, which in turn has to finish before getUserInfo()
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.
This approach allows you to execute requests in parallel.
this.userService.getUserId()
.switchMap(userResult => Observable.forkJoin(
[
Observable.of(userResult),
this.userService.getUserPermission(userResult.id),
this.userService.getUserInfo(userResult.id)
]
))
.map(results => ({
id: results[0].id,
name: results[0].name,
permissions: results[1].permissions,
info: results[2].info
}))
.subscribe(v => console.log('forkJoin:', v));
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 both getUserPermission()
and getUserInfo()
will start running in parallel.
Both methods will return an object with the following structure:
{
"id": 3,
"name": "Bob"
"permissions": [
"user",
"admin"
],
"info": "is a nice person"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With