您好,Angular非常新。我有大约4个数据库查询,每个都是Subscriptions(rxjs/Rx)
。所以我知道我需要取消订阅每个订阅以节省内存泄漏。我怎样才能优化呼叫?我的意思是,我不想打电话给每个订阅并逐个取消订阅。我想在一次通话中完成所有取消订阅。对不起,如果它是一个愚蠢的问题。任何想法的家伙?在此先感谢取消订阅订阅的最简单方法Angular
3
A
回答
4
subscriptions = Subscription[];
someMethod() {
this.subscriptions.push(http.get(...).map(...).subscribe(...));
}
ngOnDestory
this.subscriptions.forEach(s => s.unsubscribe());
}
当observable完成时,取消订阅是多余的。取消订阅仅适用于继续发射事件而未完成的观测值。
如果您只想接收单个事件(或其他数量有限的事件),则可以通过使用像take(x)
这样的操作符,然后在x
事件后完成可观察事件来控制您订阅的可观察事件何时完成。
0
还有做另一种有趣的方式:
@Component({ ... })
export class SomeComponent implements OnInit, OnDestroy {
private componentDestroyed$ = new Subject();
...
ngOnInit() {
this.yourObs1$.takeUntil(componentDestroyed$).subscribe(...);
this.yourObs2$.takeUntil(componentDestroyed$).subscribe(...);
this.yourObs3$.takeUntil(componentDestroyed$).subscribe(...);
...
this.yourObsX$.takeUntil(componentDestroyed$).subscribe(...);
}
ngOnDestroy() {
this.componentDestroyed$.next();
this.componentDestroyed$.complete();
}
}
在这里,你甚至都不需要保持一个订阅,你的阅读方式的轨道是更友好的开发(我认为)。
Ben Lesh在Medium上解释它,我喜欢这种方式取消订阅!
0
export class BaseComponent implements OnDestroy {
protected alive$: Subject<void> = new Subject<void>();
ngOnDestroy(): void {
// console.log("unsubscribing base component");
this.alive$.next();
this.alive$.complete();
}
}
export class EveryComponent extends BaseComponent {
this.AllObs1$.takeUntil(this.alive$).subscribe(...);
}
相关问题
- 1. 订阅取消订阅()
- 2. Angular - 无法从事件取消订阅()
- 3. 取消订阅socket.io中的订阅
- 4. RxJava:不会调用订阅的取消订阅()方法
- 5. Angular 2通过按钮订阅/取消订阅
- 6. 主题<any>捕获订阅和取消订阅方法
- 7. 如何取消订阅socket.io订阅?
- 8. Rxjs - 重新订阅取消订阅Observable
- 9. 如何取消订阅Weak订阅MvvmCross
- 10. 订阅/取消订阅VS Create/TakeUntil?
- 11. 取消订阅/订阅活动危险?
- 12. 订阅和取消订阅活动
- 13. 如何取消订阅NServiceBus订阅?
- 14. 动态订阅/取消订阅活动
- 15. SerialPort.DataReceived重复订阅/取消订阅
- 16. 订阅Angular的另一个订阅
- 17. 无法取消订阅PubNub
- 18. 取消iOS订阅
- 19. Android订阅取消
- 20. Angular订阅,我如何制作方法订阅
- 21. 多播代表订阅/取消订阅按钮单击事件
- 22. 简单的RSS订阅
- 23. 测试订阅observable的方法 - Angular 2
- 24. 收取PayPal订阅取消
- 25. 取消Elm中的订阅
- 26. 取消订阅的问题
- 27. 订阅/取消订阅(添加/删除)到扩展方法内部的事件
- 28. RxSwift - 订阅方法
- 29. Spring STOMP订阅的最佳实践 - 订阅消息确认
- 30. 最简单的方法来保存外部RSS订阅
阅读这可能帮助:https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87 – cartant
您不需要退订http://stackoverflow.com/questions/35042929/do -you-need-to-unsubscribe-from-angular-2-http-calls-to-prevent-memory-leak –