![](/img/trans.png)
[英]How can you combine two regular expressions in one pattern with Pipe in Angular 8?
[英]How to combine get .pipe takeUntil and subscribe into one function in Angular with RxJX?
在Angular中,每次需要查询一个端点时,都需要调用这段代码:
this.service.getSomeData()
.pipe(takeUntil(this.onDestroy$))
.subscribe((message: any) => {
some code here;
}
takeUntil 是组件中的 function 在组件被销毁时取消订阅。
如何重构上面的代码,以便每次使用资源时都不需要输入所有这些? 所以最后看起来像这样(或多或少?):
this.service.getSomeData(
(message: any) => {
some code here;
}
)
一种选择是在模板中使用异步 pipe 来管理订阅
data$ = this.service.getSomeData();
并在您的模板中
<ng-container *ngIf="data$ | async as data">
{{ data | json }}
You can use the template variable data here that magically updates every time data$
emits and no need to unsubscribe as the async pipe manages the subscription for you
</ng-container>
如果 observable 发出的数据不是模板所需的形状,则使用 map function
data$ = this.service.getSomeData().pipe(map(data => functionThatTransformsData(data)));
您可以在此处阅读我在 state 管理库中使用的模式https://medium.com/@adrianbrand/angular-state-management-with-rxcache-468a865fc3fb
通常,在从视图/dom 卸载某些组件后,您的服务不必被销毁/禁用。 把它们当作一层代码来执行一些数据转换或获取。
问:为什么每个人都使用takeUntil(this.destroyed$)
或this.subscription.unsubscribe()
?
答:只要至少有一个订阅者, Observable
就会存在。 因此,如果您有一些长期存在的可观察对象在某些操作后没有立即完成,您将有 memory 泄漏(Angular 可以多次创建/初始化每个组件)。 说到Angular
的http
,所有的get
, post
, put
和delete
调用都是在后端调用完成后完成的。 这意味着您不必在onDestroy
挂钩中添加unsubscribe
或使用takeUntil
。
如果您已建立Websocket
连接并正在收听一些消息,则您的 stream 将变得持久,并且订阅此消息的每个组件都应在onDestroy
周期内取消订阅。 如果你不这样做,Angular 可以多次初始化你的组件(这通常发生在*ngIf=""
语句中)并且多个订阅被创建但永远不会被销毁。 这会导致 memory 泄漏。
不幸的是,这是大多数 Angular 项目的常见问题,可以通过手动unsubscribe
/ takeUntil
或使用async
pipe 在组件被销毁后自动执行unsubscribe
来解决。
我很高兴你问这个,我遇到了这个Angular AutoUnsubscribe (我引用这个是因为我发现实现这个的逻辑真的很漂亮。)
它相对易于使用,并且适用于所有可声明对象(显然是管道、指令和组件。)
现在省略订阅和取消订阅部分(我不会建议),它非常简单,直截了当。
早些时候你有类似的东西
getSomeData(): Observable<any> {
// for eg
return this.http.get();
}
您必须将其更改为:
getSomeData(callback, onDestroy$): Observable<any> {
this.http.get(...).pipe(takeUntil(onDestroy$)).subscribe(val => callback(val));
}
然后我们就能得到我们最终想要的东西。 干杯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.