【发布时间】:2019-03-24 19:48:32
【问题描述】:
我最近学会了避免内存泄漏,我需要在我的组件中取消订阅。为此,我实现了OnDestroy,但这在导航时引起了问题。
错误错误:未捕获(承诺):TypeError:无法读取未定义的属性“取消订阅” TypeError:无法读取未定义的属性“取消订阅”
如果我不退订导航成功完成。
我的印象是 ngOnDestroy 只有在其他所有事情都完成后才会发生,显然情况并非如此。
我显然做错了什么,但我不知道导航离开页面时如何取消订阅?
export class PropertyFormMapperComponent implements OnInit, OnDestroy {
private _routeSubscription: any;
private _getPropertySubscription: any;
constructor(
private _route: ActivatedRoute,
private _propertyFormFileService: PropertyFormFileService,
private _router: Router
) { }
ngOnInit(): void {
this._routeSubscription = this._route.params.subscribe(params => {
this._id = params['id'];
this._getPropertySubscription = this._propertyService.getProperty(this._id).subscribe(property => {
...do stuff...
});
});
}
ngOnDestroy(): void {
this._routeSubscription.unsubscribe();
this._getPropertySubscription.unsubscribe();
}
private onCreate(event: any): void {
this._propertyService.postProperty(property, 1).subscribe(
response => {
...do stuff...
this._router.navigate(['home']);
},
error => {
...other stuff...
}
);
}
}
【问题讨论】:
-
您能否将值记录到
ngOnDestroy中的控制台,以查找两个订阅中的哪一个未定义? -
嵌套的未定义 -
_getPropertySubscription。在另一个订阅中订阅是一种糟糕的 rxjs 实践,也是初学者常犯的错误。您应该使用更高阶的 rxjs 方法组合流来组合流 -
您可以在调用
unsubscribe... 之前检查是否定义了 subscription -
@codeepic 谢谢你的建议,
combine the streams using higher order rxjs methods是什么意思,按照你的建议,我现在正在审查提到concat的syntaxsuccess.com/viewarticle/…,这是你的意思吗?跨度> -
是的,
concatMap更具体。您使用哪个版本的rxjs?我希望后一个,所以我的答案中的语法对你有用->较新版本的管道运算符函数而不是.do()使用.tap(),因为do是JavaScript中的保留字。
标签: angular rxjs angular4-router