---------------------------------------------------------------
Cory Rylan

Nov 15, 2016 
Updated Feb 25, 2018 - 5 min readangular rxjs

This article has been updated to the latest version of Angular 7. The content is still likely be applicable for Angular 2 or other previous versions.

This article has been updated to use the new RxJS Pipeable Operators which is the new default for RxJS 6.

A typical pattern we run into with single page apps is to gather up data from multiple API endpoints and then display the gathered data to the user. 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.

Let’s start with a simple HTTP request using the Angular Http service.



import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http'; @Component({
selector: 'app-root',
templateUrl: 'app/app.component.html'
})
export class AppComponent { constructor(private http: HttpClient) { } ngOnInit() {
this.http.get('/api/people/1').subscribe(json => console.log(json));
}
}

In our app, we have just a single component that pulls in Angular’s Http service via Dependency Injection. Angular will give us an instance of the Http service when it sees the signature in our component’s constructor.

Now that we have the service we call the service to fetch some data from our test API. We do this in the ngOnInit. This is a life cycle hook where its ideal to fetch data. You can read more about ngOnInit in the docs. For now, let’s focus on the HTTP call. We can see we have http.get() that makes a GET request to /api/people/1. We then call subscribe to subscribe to the data when it comes back. When the data comes back, we just log the response to the console. So this is the simplest snippet of code to make a single request. Let’s next look at making two requests.

Subscribe

In our next example, we will have the following use case: We need to retrieve a character from the Star Wars API. To start, we have the id of the desired character we want to request.

When we get the character back, we then need to fetch that character’s homeworld from the same API but a different REST endpoint. This example is sequential. Make one request then the next.

Angular Form Essentials

Learn the essentials to get started creating amazing forms with Angular, get the E-Book now!



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() {
this.http.get('/api/people/1').subscribe(character => {
this.http.get(character.homeworld).subscribe(homeworld => {
character.homeworld = homeworld;
this.loadedCharacter = character;
});
});
}
}

Looking at the ngOnInit method, we see our HTTP requests. First, we request to get a user from /api/user/1. Once loaded we the make a second request a fetch the homeworld of that particular character. Once we get the homeworld, we add it to the character object and set the loadedCharacter property on our component to display it in our template. This works, but there are two things to notice here. First, we are starting to see this nested pyramid structure in nesting our Observables which isn’t very readable. Second, our two requests were sequential. So let’s say our use case is we just want to get the homeworld of our character and to get that data we must load the character and then the homeworld. We can use a particular operator to help condense our code above.

MergeMap

In this example, we will use the mergeMap operator. Let’s take a look at the code example first.



import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { mergeMap } from 'rxjs/operators'; @Component({
selector: 'app-root',
templateUrl: 'app/app.component.html'
})
export class AppComponent {
homeworld: Observable<{}>;
constructor(private http: HttpClient) { } ngOnInit() {
this.homeworld = this.http.get('/api/people/1').pipe(
mergeMap(character => this.http.get(character.homeworld))
);
}
}

In this example, we use the mergeMap also known as flatMap to map/iterate over the Observable values. So in our example when we get the homeworld, we are getting back an Observable inside our character Observable stream. This creates a nested Observable in an Observable. The mergeMap operator helps us by subscribing and pulling the value out of the inner Observable and passing it back to the parent stream. This condenses our code quite a bit and removes the need for a nested subscription. This may take a little time to work through, but with practice, it can be a handy tool in our RxJS tool belt. Next, let’s take a look at multiple parallel requests with RxJS.

ForkJoin

In this next example, we are going to use an operator called forkJoin. If you are familiar with Promises, this is very similar to Promise.all(). The forkJoin() operator allows us to take a list of Observables and execute them in parallel. Once every Observable in the list emits a value, the forkJoin will emit a single Observable value containing a list of all the resolved values from the Observables in the list. In our example, we want to load a character and a characters homeworld. We already know what the ids are for these resources so we can request them in parallel.



import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { forkJoin } from "rxjs/observable/forkJoin"; @Component({
selector: 'app-root',
templateUrl: 'app/app.component.html'
})
export class AppComponent {
loadedCharacter: {};
constructor(private http: HttpClient) { } ngOnInit() {
let character = this.http.get('https://swapi.co/api/people/1');
let characterHomeworld = this.http.get('http://swapi.co/api/planets/1'); forkJoin([character, characterHomeworld]).subscribe(results => {
// results[0] is our character
// results[1] is our character homeworld
results[0].homeworld = results[1];
this.loadedCharacter = results[0];
});
}
}

In our example, we capture the character and characterHomeworld Observable in variables. Observables are lazy, so they won’t execute until someone subscribes. When we pass them into forkJoin the forkJoin operator will subscribe and run each Observable, gathering up each value emitted and finally emitting a single array value containing all the completed HTTP requests. This is a typical pattern with JavaScript UI programming. With RxJS this is relatively easy compared to using traditional callbacks.

With the mergeMap/flatMap and forkJoin operators we can do pretty sophisticated asynchronous code with only a few lines of code. Check out the live example below!

Angular Multiple HTTP Requests with RxJS的更多相关文章

  1. [RxJS + AngularJS] Sync Requests with RxJS and Angular

    When you implement a search bar, the user can make several different queries in a row. With a Promis ...

  2. [Angular] Intercept HTTP requests in Angular

    Being able to intercept HTTP requests is crucial in a real world application. Whether it is for erro ...

  3. [Angular] Bind async requests in your Angular template with the async pipe and the "as" keyword

    Angular allows us to conveniently use the async pipe to automatically register to RxJS observables a ...

  4. [Vue-rx] Cache Remote Data Requests with RxJS and Vue.js

    A Promise invokes a function which stores a value that will be passed to a callback. So when you wra ...

  5. [Angular 2] Managing State in RxJS with StartWith and Scan

    The scan operator in RxJS is the main key to managing values and states in your stream. Scan behaves ...

  6. [RxJS] Avoid mulit post requests by using shareReplay()

    With the shareReplay operator in place, we would no longer fall into the situation where we have acc ...

  7. [Angular2 Form] Use RxJS Streams with Angular 2 Forms

    Angular 2 forms provide RxJS streams for you to work with the data and validity as it flows out of t ...

  8. RxJS之Subject主题 ( Angular环境 )

    一 Subject主题 Subject是Observable的子类.- Subject是多播的,允许将值多播给多个观察者.普通的 Observable 是单播的. 在 Subject 的内部,subs ...

  9. RxJS之工具操作符 ( Angular环境 )

    一 delay操作符 源Observable延迟指定时间,再开始发射值. import { Component, OnInit } from '@angular/core'; import { of ...

随机推荐

  1. gradle中 使用lombok

    plugins {     id 'java'     id "io.franzbecker.gradle-lombok" version "3.1.0"    ...

  2. Information retrieval (IR class1)

    1. 什么是IR? IR与数据库的区别? 答:数据库是检索结构化的数据,例如关系数据库:而信息检索是检索非结构化/半结构化的数据,例如:一系列的文本.信息检索是属于NLP(自然语言处理)里面最实用的一 ...

  3. SVN常用命令--Mac端【转载】

    * 版本库布局 1. trunk主干 trunk就是开发的主线,一般项目都是导入到主线来开发的. 2. branches分支 branches一般是trunk某个版本的拷贝,如果你想在某一段时间单独对 ...

  4. PHP学习之迭代生成器

    生成器的核心是一个yield关键字,一个生成器函数看起来像一个普通的函数,不同的是.普通函数返回一个值,而一个生成器可以yield生成许多它所需要的值.生成器函数被调用时,返回的是一个可以被遍历的对象 ...

  5. gitlab LFS 的应用实践

    今天看到的gitlab LFS的文档,将自己的理解整理成博客,加深自己的印象.具体gitlab LFS的介绍可以直接百度了,不在这里详细阐述.只提一下他的作用:LFS就是Large File Stor ...

  6. 一文让你明白Redis持久化

    网上虽然已经有很多类似的介绍了,但我还是自己总结归纳了一下,自认为内容和细节都是比较齐全的. 文章篇幅有 4k 多字,货有点干,断断续续写了好几天,希望对大家有帮助.不出意外地话,今后会陆续更新 Re ...

  7. 【Trie】L 语言

    [题目链接]: https://loj.ac/problem/10053 [题意]: 给出n个模式串.请问文本串是由多少个模式串组成的. [题解]: 当我学完AC自动机后,发现这个题目也太简单了吧. ...

  8. ShellCode 最小化编译优化

    1.生成ShellCode [root@localhost ~]# msfvenom -a x86 --platform Windows \ > -p windows/meterpreter/r ...

  9. 基于白名单的Payload

    利用 Msiexec 命令DLL反弹 Msiexec是Windows Installer的一部分.用于安装Windows Installer安装包(MSI),一般在运行Microsoft Update ...

  10. 使用jenkins 构建时,字体图标报错的问题。

    最近一个项目开发中,我们在本地进行项目打包时,可以正常打包. 但是在使用jenkins构建时,一直报错,提示无法加载字体文件.can't resolve module '....xxxx.TTF ' ...