javascript - 如何对 HttpClient.get 返回的 Observable 实现副作用?

标签 javascript angular angular5 observers

有人知道如何在 Angular 的 HttpClient.get 方法返回的观察者上使用 RxJS do 运算符吗?

版本:

  • Angular :5.2.1
  • rxjs:5.5.6

使用这个版本的 Angular 我不能这样做:

import { HttpClient } from '@angular/common/http';

...

constructor(
  private http: HttpClient,
) { }

...

this.http.get<Item>(url)
  .do(res => console.log(JSON.stringify(res)))
  .share();

相反,我必须添加带有管道的新步骤。我可以使用 switchMapmapshare 来完成,但我不知道如何使用 do.

我发现我可以 import { _do } from 'rxjs/operator/do';,但是当我尝试像这样使用它时:

this.http.get<Item>(url)
  .pipe(_do(res => console.log(JSON.stringify(res)))

或者像这样:

const observable = this.http.get<Item>(url);
observable.pipe(_do(observable, res => console.log(JSON.stringify(res)}));

我遇到错误:

[ts] The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<{}>'.

最佳答案

作为pipeable operators文档解释说,pipeable do 与其他几个一起重命名为 tap。这样做是为了避免与保留的 JavaScript 关键字发生冲突。

管道运算符应该被导入为

import { tap } from 'rxjs/operators/tap';

请注意,管道运算符位于 rxjs/operators/... 中,而 rxjs/operator/... 导入用于修补 Observable。原型(prototype).

没有人担心会阻止 do 运算符在某些 Angular 版本中使用。两种导入样式都受支持且有效,只要开发人员了解补丁运算符和管道运算符之间存在某些差异,使得后者在某些情况下更可取。它们在 documentation page 上有解释:

  1. Any library that imports a patch operator will augment the Observable.prototype for all consumers of that library, creating blind dependencies. If the library removes their usage, they unknowingly break everyone else. With pipeables, you have to import the operators you need into each file you use them in.

  2. Operators patched directly onto the prototype are not "tree-shakeable" by tools like rollup or webpack. Pipeable operators will be as they are just functions pulled in from modules directly.

  3. Unused operators that are being imported in apps cannot be detected reliably by any sort of build tooling or lint rule. That means that you might import scan, but stop using it, and it's still being added to your output bundle. With pipeable operators, if you're not using it, a lint rule can pick it up for you.

  4. Functional composition is awesome. Building your own custom operators becomes much, much easier, and now they work and look just like all other operators from rxjs. You don't need to extend Observable or override lift anymore.

关于javascript - 如何对 HttpClient.get 返回的 Observable 实现副作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48361439/

相关文章:

javascript - jQuery - 查找最后选择的元素

c# - 如何使用 jQuery 在对话框中打开页面?

angular - 第二次点击 routerLink 后重新加载页面

javascript - 更新 ngx-translate 加载器中的翻译

Angular 5组件测试选择和触发事件

javascript - Node.js Promise 代码在一个实例中有效,但在另一个实例中无效

javascript - 获取选择器中的第一个和最后一个对象

angular - 如何使整个 Angular 组件可点击

angular-material - 'mat-expansion-panel' 在以 Angular 5 进行生产构建时不是已知元素

angular - 如何在 Angular 5 中嵌套超过 2 级的子路由?