【问题标题】:RxJS Pipe method utilizationRxJS Pipe 方法利用
【发布时间】:2020-07-17 06:50:58
【问题描述】:
const apiData = ajax('/api/data').pipe(
  retry(3), // Retry up to 3 times before failing
  map(res => {
    if (!res.response) {
      throw new Error('Value expected!');
    }
    return res.response;
  }),
  catchError(err => of([]))
);

我正在学习 angular 并且从 angular 官方网站我看到了这段代码。 .pipe() 函数是干什么用的?

【问题讨论】:

  • 异步模式下可观察的返回数据,您可以更改此响应,例如您希望收到类似data:{prop1:'prop1',array:[0,1,2]} 的内容,而您只想要“array”的值,因此您使用“map”来转换响应:pipe(map(res=>res.array)) 从 Rxjs 6 开始,您使用 pipe(operator1(res),operator2(res) ,....),其中 operator# 是不同的运算符 (swichMap,map,takeWhile,concat,bitwise...)。结果是一个新的 Observable,当我们订阅它时返回我们想要的响应
  • 这能回答你的问题吗? What is pipe() function in Angular

标签: angular rxjs reactive-programming


【解决方案1】:

RxJS 在 OBSERVABLES 的核心概念上实现了反应式编程范式。

如果你已经知道 javascript 的 Promises,那么 observables 会有一些细微的differences

  • Promise 是急切的,而 Observable 是惰性的;
  • Promise 始终是异步的,而 Observable 可以是同步的也可以是异步的;
  • Promise 可以提供单个值,而 Observable 是值流(从 0 到多个值);

说到这里,RxJS 库提供了很多名为Creation Operators 的函数 这些函数可用于从非常常见的 JS 行为开始创建新的 OBSERVABLES 例如 AJAX 调用(异步 javascript 和 xml)

import { ajax } from 'rxjs/ajax';

// Create an Observable that will create an AJAX request
const apiData = ajax('/api/data');

在这类算子上,我们可以应用Pipeable Operators。 它们之间的区别在于它们必须应用于现有的运算符, 创建一个新的。

想象一系列这样的可管道操作符的串联,代码将被写成:

pipeableOperator3(pipeableOperator2(pipeableOperator(creatorOperator())))

出于这个原因,Observables 有一个名为 .pipe() 的方法,它可以完成同样的事情,同时更容易阅读:

creatorOperator().pipe(
  pipeableOperator1(),
  pipeableOperator2(),
  pipeableOperator3());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-18
    • 2020-10-22
    • 2019-06-24
    • 2021-06-07
    • 2021-11-30
    • 1970-01-01
    • 2018-10-21
    • 2021-10-29
    相关资源
    最近更新 更多