Home >Web Front-end >JS Tutorial >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
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
and model
strings.
When I modified the data for the second time, I got an array with only brand
being Porsche
.
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.
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
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.
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!