正如获奖答案自动引用subscriptions
to ,ActivatedRoute
Angular一样unsubscribes
。
当不再需要路由组件并且注入的 ActivatedRoute 随之消亡时,Router 会销毁路由组件。
如果您想知道如何unsubscribe
从Observables
:
import { Component,
OnInit,
OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
// Type
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.scss']
})
export class ExampleComponent implements OnInit, OnDestroy {
paramsSubscription : Subscription;
constructor(private activatedRoute : ActivatedRoute) { }
/* Angular lifecycle hooks
*/
ngOnInit() {
console.log("Component initialized");
this.paramsSubscription = this.activatedRoute.params.subscribe( params => {
});
}
ngOnDestroy() {
console.log("Component will be destroyed");
this.paramsSubscription.unsubscribe();
}
}