我想弄清楚爲什麼我看到的所有Angular應用程序都將訂閱分配給一個變量,只能通過ngOnDestroy()取消訂閱。例如:如果您未將其分配給變量,會發生什麼情況?
export class ViewBookPageComponent implements OnDestroy {
actionsSubscription: Subscription;
constructor(store: Store<fromRoot.State>, route: ActivatedRoute) {
this.actionsSubscription = route.params
.select<string>('id')
.map(id => new book.SelectAction(id))
.subscribe(store);
}
ngOnDestroy() {
this.actionsSubscription.unsubscribe();
}
}
如果我只是完全刪除actionsSubscription,會發生什麼?訂閱還會被創建但不會被銷燬?在下面的情況下,您仍然會產生副作用,但不必麻煩取消訂閱。垃圾收集所需的actionsSubscription也是如此?
export class ViewBookPageComponent {
constructor(store: Store<fromRoot.State>, route: ActivatedRoute) {
route.params
.select<string>('id')
.map(id => new book.SelectAction(id))
.subscribe(store);
}
}
感謝您的快速響應!還有一個問題:如果我將.subscribe()放在一起,並且僅僅使用SelectAction副作用保留.map(),那該怎麼辦?由於沒有用戶,觀察者會不會繼續發射,還是會與組件一起死亡? –
從angular.io開始,「subscribe()方法返回一個Subscription,一個Subscription不是另一個Observable,它是Observables的行尾,你不能再調用map()或再次調用subscribe()。訂閱對象具有不同的用途,用其主要方法表示,取消訂閱。「簡而言之,可觀察性直到訂閱使用訂閱()纔會開始工作。 – Nehal
明白了。謝謝。 –