有人知道如何在 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();
相反,我必须添加带有管道的新步骤。我可以使用 switchMap
、map
或 share
来完成,但我不知道如何使用 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 上有解释:
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.
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.
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.
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/