Anguar 小技巧 #4

发布: (2026年1月7日 GMT+8 17:43)
3 min read
原文: Dev.to

Source: Dev.to

介绍

一些使用 Angular 的技巧——来自前端开发者(第 4 部分)。
这些技巧假设你已经有 Angular 经验,所以我们不会深入探讨 RxJS 基础。

使用 concatMap 顺序处理数组

当你有一个值数组并且需要为每个项目执行异步操作时,concatMap 是完美的选择。它会 顺序 处理每个项目,等待前一个异步操作完成后才继续下一个。

import { from, of } from 'rxjs';
import { concatMap, tap, delay } from 'rxjs/operators';

const numbers = [1, 2, 3];

const test$ = from(numbers).pipe(
  concatMap(number => {
    return of(null).pipe(
      tap(() => console.log(number)),
      delay(2000)
    );
  })
);

使用这段代码,from 源的每一次发射都会等到 concatMap 内部的异步操作完成后才处理下一个值。console.log 语句会在每个数字后延迟 2 秒后执行。

添加最终的同步操作

如果你需要在 所有项目处理完毕后 再执行另一个同步操作,请将额外的操作符 放在 concatMap 之后。例如,在 concatMap 之后直接添加 tap,它会对每个发射的值运行一次:

const test$ = from(numbers).pipe(
  concatMap(number => {
    return of(null).pipe(
      tap(() => console.log(number)),
      delay(2_000)
    );
  }),
  tap(() => console.log('This goes here!'))
);

输出将会是:

1
This goes here!
2
This goes here!
3
This goes here!

为了确保最终的操作 只执行一次,在所有值处理完毕后再运行 tap,可以在最终的 tap 之前插入 last() 操作符:

const test$ = from(numbers).pipe(
  concatMap(number => {
    return of(null).pipe(
      tap(() => console.log(number)),
      delay(2_000)
    );
  }),
  last(),
  tap(() => console.log('This goes here!'))
);

现在控制台会显示:

1
2
3
This goes here!

"This goes here!" 的日志只会执行一次,且在所有数字日志完成后才出现。

结论

当你需要顺序处理异步操作时,concatMap 非常有用。通过与 last 等操作符结合使用,你可以控制后续同步操作的执行时机。

以上就是关于 Angular 小技巧的第 4 篇博客——希望对你有帮助!我们下篇文章再见。

Back to Blog

相关文章

阅读更多 »

Angular 21 — 新功能与变更

Angular 21 专注于简化、性能和现代响应式模式。它不是添加花哨的 API,而是强化 Angular 开发者已经使用的……

React 编码挑战:卡片翻转游戏

React 卡片翻转游戏 – 代码 tsx import './styles.css'; import React, { useState, useEffect } from 'react'; const values = 1, 2, 3, 4, 5; type Card = { id: numb...