Questions tagged «angular-component-life-cycle»

21
Angular / RxJs我应该何时退订`Subscription`
我应该何时存储Subscription实例并unsubscribe()在NgOnDestroy生命周期中调用,何时可以忽略它们? 保存所有订阅会在组件代码中带来很多麻烦。 HTTP客户端指南会忽略这样的订阅: getHeroes() { this.heroService.getHeroes() .subscribe( heroes => this.heroes = heroes, error => this.errorMessage = <any>error); } 同时,《路线与导航指南》指出: 最终,我们将导航到其他地方。路由器将从DOM中删除此组件并销毁它。我们需要在此之前进行自我清理。具体来说,我们必须在Angular销毁组件之前取消订阅。否则可能会导致内存泄漏。 我们取消订阅Observable该ngOnDestroy方法。 private sub: any; ngOnInit() { this.sub = this.route.params.subscribe(params => { let id = +params['id']; // (+) converts string 'id' to a number this.service.getHero(id).then(hero => this.hero = hero); }); } …
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.