1
到現在爲止,我一直在做下面的訂閱的值賦給我的班屬性:分配值,而不突變
export class ExampleComponent implements OnInit {
exampleId: string;
constructor(public route: ActivatedRoute) {
this.route.params.subscribe((params: Params) => this.exampleId = params.id);
}
ngOnInit() {
// Do something with exampleId here...
}
}
在努力擺脫突變,更多地轉向不變性;我希望將該訂閱返回的值分配給exampleId
屬性,而無需在構造函數中這樣做。
什麼是最好的方式去做這件事?
你可以在OnInit生命週期中做到這一點 –
這仍然會改變原來的屬性定義。我需要在創建屬性時分配值。 –
有一個快照替代獲取路徑參數,而不使用可觀察的訂閱[鏈接](https://angular.io/guide/router#snapshot-the-no-observable-alternative) –