Table of Contents
map
MergeMap
SwitchMap
ConcatMap
总结
Home Web Front-end JS Tutorial A brief discussion on how RxJS maps data operations in Angular

A brief discussion on how RxJS maps data operations in Angular

Jul 06, 2021 am 11:56 AM
angular rxjs Data operations

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));
Copy after login

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.

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));
Copy after login

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)));
Copy after login

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));
Copy after login

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));
Copy after login

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));
Copy after login

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();
Copy after login

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));
Copy after login

getData函数的随机延迟在1到10000毫秒之间。通过浏览器日志,可以看到mapmergeMap操作符将记录返回的任何值,而不遵循原始顺序。concatMap记录的值与它们开始时的值相同。

总结

将数据映射到所需的格式是一项常见的任务。RxJS附带了一些非常简洁的操作符,可以很好的完成这项工作。

概括一下:map用于将normal值映射为所需的任何格式。返回值将再次包装在一个可观察对象中,因此可以在数据流中继续使用它。当必须处理一个“内部”观察对象时,使用mergeMapswitchMapconcatMap更容易。如果只是想将数据转成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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

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

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

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!

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

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

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

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

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

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 How to use PHP to implement batch processing and data batch operations Sep 06, 2023 am 10:46 AM

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.

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

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!

What should I do if the project is too big? How to split Angular projects reasonably? What should I do if the project is too big? How to split Angular projects reasonably? Jul 26, 2022 pm 07:18 PM

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!

See all articles