A brief discussion on how RxJS maps data operations in Angular
#Map
Data is a common operation during program development. When using RxJS
to generate data streams in your code, you will most likely end up needing a way to map the data into whatever format is needed. RxJS
provides regular map
functions, as well as mergeMap
, switchMap
and concatMap
functions. are handled slightly differently. [Related tutorial recommendations: "angular tutorial"] The
map
map
operator is the most common. For each value emitted by an Observable
, a function can be applied to modify the data. The return value will be re-released as an Observable
in the background so that it can be continued to be used in the stream. It works very similarly to using it with an array.
The difference is that an array will always be just an array, whereas when mapping, you will get the current index value in the array. For observable
, the type of data can be of various types. This means that some additional operations may need to be done in the Observable map
function to obtain the desired results. Look at the following example: :
import { of } from "rxjs"; import { map } from "rxjs/operators"; // 创建数据 const data = of([ { brand: "保时捷", model: "911" }, { brand: "保时捷", model: "macan" }, { brand: "法拉利", model: "458" }, { brand: "兰博基尼", model: "urus" } ]); // 按照brand model的格式输出,结果:["保时捷 911", "保时捷 macan", "法拉利 458", "兰博基尼 urus"] data.pipe(map(cars => cars.map(car => `${car.brand} ${car.model}`))).subscribe(cars => console.log(cars)); // 过滤数据,只保留brand为porsche的数据,结果:[{"brand":"保时捷","model":"911"},{"brand":"保时捷","model":"macan"}] data.pipe(map(cars => cars.filter(car => car.brand === "保时捷"))).subscribe(cars => console.log(cars));
First create an observable with a series of cars. Then subscribe to this observable 2 times.
When I modified the data for the first time, I got an array connected by the
brand
andmodel
strings.When I modified the data for the second time, I got an array with only
brand
beingPorsche
.
In both examples, use the Observable
map operator to modify the data emitted by the Observable
. The modified result is returned, and then the map
operator encapsulates the result into an observable object so that it can be subscribe
later.
MergeMap
Now suppose there is a scenario where there is an observable object that emits an array. For each item in the array, it needs to be retrieved from The server gets the data.
You can do this by subscribing to the array, then setting up a map to call a function that handles the API call, subscribing to its results. As follows:
import { of, from } from "rxjs"; import { map, delay } from "rxjs/operators"; const getData = param => { return of(`检索参数: ${param}`).pipe(delay(1000)); }; from([1, 2, 3, 4]) .pipe(map(param => getData(param))) .subscribe(val => console.log(val));
map
function returns the value of the getData
function. In this case, it's observable. But this creates a problem: now we have an extra observable to deal with.
To clarify this further: from([1,2,3,4])
As an "external" observable, the result of getData()
as "Internal" observables. In theory, both external and internal observables must be accepted. It could look like this:
import { of, from } from "rxjs"; import { map, delay } from "rxjs/operators"; const getData = param => { return of(`检索参数: ${param}`).pipe(delay(1000)); }; from([1, 2, 3, 4]) .pipe(map(param => getData(param))) .subscribe(val => val.subscribe(data => console.log(data)));
As you can imagine, this is far from the ideal situation of having to call Subscribe
twice. This is where mergeMap
comes into play. MergeMap
is essentially a combination of mergeAll
and map
. MergeAll
is responsible for subscribing to the "inner" observable object. When MergeAll
merges the values of the "inner" observable object into the "outer" observable object, there is no need to subscribe twice. As follows:
import { of, from } from "rxjs"; import { map, delay, mergeAll } from "rxjs/operators"; const getData = param => { return of(`检索参数: ${param}`).pipe(delay(1000)); }; from([1, 2, 3, 4]) .pipe( map(param => getData(param)), mergeAll() ) .subscribe(val => console.log(val));
This is much better, mergeMap
will be the best solution for this problem. Here is the complete example:
import { of, from } from "rxjs"; import { map, mergeMap, delay, mergeAll } from "rxjs/operators"; const getData = param => { return of(`检索参数: ${param}`).pipe(delay(1000)); }; // 使用 map from([1, 2, 3, 4]) .pipe(map(param => getData(param))) .subscribe(val => val.subscribe(data => console.log(data))); // 使用 map 和 mergeAll from([1, 2, 3, 4]) .pipe( map(param => getData(param)), mergeAll() ) .subscribe(val => console.log(val)); // 使用 mergeMap from([1, 2, 3, 4]) .pipe(mergeMap(param => getData(param))) .subscribe(val => console.log(val));
SwitchMap
SwitchMap
has similar behavior, it will also subscribe to the internal observable. However, switchMap
is a combination of switchAll
and map
. SwitchAll
Cancel previous subscription and subscribe to new subscription. In the above scenario, one wants to perform an API call for each item in the "external" observable array, but switchMap
doesn't work very well because it will cancel the first 3 subscriptions and only Process the last subscription. This means that only one result will be obtained. The complete example can be seen here:
import { of, from } from "rxjs"; import { map, delay, switchAll, switchMap } from "rxjs/operators"; const getData = param => { return of(`retrieved new data with param ${param}`).pipe(delay(1000)); }; // 使用 a regular map from([1, 2, 3, 4]) .pipe(map(param => getData(param))) .subscribe(val => val.subscribe(data => console.log(data))); // 使用 map and switchAll from([1, 2, 3, 4]) .pipe( map(param => getData(param)), switchAll() ) .subscribe(val => console.log(val)); // 使用 switchMap from([1, 2, 3, 4]) .pipe(switchMap(param => getData(param))) .subscribe(val => console.log(val));
Although switchMap
does not work for the current scenario, it works for other scenarios. This would come in handy, for example, if you combine a list of filters into a data flow and perform an API call when the filter is changed. If the previous filter change is still being processed and the new change has been completed, then it will cancel the previous subscription and start a new one on the latest change. An example can be seen here:
import { of, from, BehaviorSubject } from "rxjs"; import { map, delay, switchAll, switchMap } from "rxjs/operators"; const filters = ["brand=porsche", "model=911", "horsepower=389", "color=red"]; const activeFilters = new BehaviorSubject(""); const getData = params => { return of(`接收参数: ${params}`).pipe(delay(1000)); }; const applyFilters = () => { filters.forEach((filter, index) => { let newFilters = activeFilters.value; if (index === 0) { newFilters = `?${filter}`; } else { newFilters = `${newFilters}&${filter}`; } activeFilters.next(newFilters); }); }; // 使用 switchMap activeFilters.pipe(switchMap(param => getData(param))).subscribe(val => console.log(val)); applyFilters();
As seen in the console, getData
logs all parameters only once. Saved 3 API calls.
ConcatMap
The last example is concatMap
. concatMap
Subscribed to the internal observable object. But unlike switchMap
, if a new observation object comes in, it will cancel the subscription of the current observation object. concatMap
will not subscribe to the next observation before the current observation object is completed. object. The advantage of this is that the order in which the observable objects emit signals is maintained. To demonstrate this:
import { of, from } from "rxjs"; import { map, delay, mergeMap, concatMap } from "rxjs/operators"; const getData = param => { const delayTime = Math.floor(Math.random() * 10000) + 1; return of(`接收参数: ${param} and delay: ${delayTime}`).pipe(delay(delayTime)); }; // 使用map from([1, 2, 3, 4]) .pipe(map(param => getData(param))) .subscribe(val => val.subscribe(data => console.log("map:", data))); // 使用mergeMap from([1, 2, 3, 4]) .pipe(mergeMap(param => getData(param))) .subscribe(val => console.log("mergeMap:", val)); // 使用concatMap from([1, 2, 3, 4]) .pipe(concatMap(param => getData(param))) .subscribe(val => console.log("concatMap:", val));
getData
函数的随机延迟在1到10000毫秒之间。通过浏览器日志,可以看到map
和mergeMap
操作符将记录返回的任何值,而不遵循原始顺序。concatMap
记录的值与它们开始时的值相同。
总结
将数据映射到所需的格式是一项常见的任务。RxJS
附带了一些非常简洁的操作符,可以很好的完成这项工作。
概括一下:map
用于将normal
值映射为所需的任何格式。返回值将再次包装在一个可观察对象中,因此可以在数据流中继续使用它。当必须处理一个“内部”观察对象时,使用mergeMap
、switchMap
或concatMap
更容易。如果只是想将数据转成Observable
对象,使用mergeMap
;如果需要丢弃旧的Observable
对象,保留最新的Observable
对象,使用switchMap
;如果需要将数据转成Observable
对象,并且需要保持顺序,则使用concatMap
。
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of A brief discussion on how RxJS maps data operations in Angular. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

Do you know Angular Universal? It can help the website provide better SEO support!

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

How to use PHP to implement batch processing and data batch operations. In the process of developing web applications, we often encounter situations where multiple pieces of data need to be processed at the same time. In order to improve efficiency and reduce the number of database requests, we can use PHP to implement batch processing and data batch operations. This article will introduce how to use PHP to implement these functions, and attach code examples for reference. Batch processing of data When you need to perform the same operation on a large amount of data, you can use PHP's loop structure for batch processing.

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!

The Angular project is too large, how to split it reasonably? The following article will introduce to you how to reasonably split Angular projects. I hope it will be helpful to you!
