我有一个带有计时器的子组件,我每 2 秒向服务器发送一次 api 调用。只要用户在页面上,我就需要执行此调用,即使他/她去参加婚礼并保持页面(父组件窗口)打开。
这是我的组件中的一些代码:
this.myTimer = Observable.timer(1, 2000);
this.myTimer
.mergeMapTo(this.myService.doSomeWork(this.myId))
.subscribe((data) => {
this.myData = data;
}, (errRes)=>{
console.log(errRes);
});
这是销毁方法:
ngOnDestroy(): void {
this.myTimer.complete();
}
我只需点击不同组件的菜单,就会看到调用 到服务器仍在发生。 我什至尝试关闭窗口(来自 chrome 浏览器的选项卡),仍然对服务器的调用仍然存在。
知道为什么 ngOnDestroy 没有被调用吗?
更新 我正在使用 "rxjs": "^5.5.12",
来自 package.json:
"dependencies": {
"@angular/animations": "^5.2.11",
"@angular/common": "^5.2.11",
"@angular/compiler": "^5.2.11",
"@angular/core": "^5.2.11",
"@angular/forms": "^5.2.11",
"@angular/http": "^5.2.11",
"@angular/platform-browser": "^5.2.11",
"@angular/platform-browser-dynamic": "^5.2.11",
"@angular/router": "^5.2.11",
"angular-file-saver": "^1.1.3",
"angular-webstorage-service": "^1.0.2",
"core-js": "^2.6.9",
"file-saver": "^2.0.2",
"jquery": "^3.4.1",
"moment": "^2.24.0",
"ngx-bootstrap": "^2.0.5",
"ngx-select-dropdown": "^1.0.1",
"ngx-select-ex": "^3.6.10",
"ngx-select-options": "^1.0.5",
"rxjs": "^5.5.12",
"web-animations-js": "^2.3.1",
"zone.js": "^0.8.29"
最佳答案
嗯.. 你可以尝试使用 RxJS 的 takeUntil运算符代替。
首先,您将 takeUntil
和 Subject
导入到您的组件中。
import { takeUntil, mergeMap } from 'rxjs/operators';
import { Subject } from 'rxjs/Subject'
下一步,
unsubscribe: Subject<void> = new Subject();
然后,
this.myTimer
.pipe(
mergeMap(this.myService.doSomeWork(this.myId)),
takeUntil(this.unsubscribe)
).subscribe((data) => {
this.myData = data;
}, (errRes)=>{
console.log(errRes);
});
请注意,takeUntil
必须是 pipe()
上的最后一个运算符,以防止任何可观察值“泄漏”。
在你的 ngOnDestroy 上,
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}
关于angular - 如何在 Angular 中正确实现 ngOnDestroy()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56672547/