如果我订阅主题,那么我必须退订。如果我订阅了一个Observable,则可以跳过退订步骤,因为据我所知它是自动完成的。
接下来的情况如何?
export class PlacesService {
private _places = new BehaviorSubject<Place[]>([
new Place(
'p1',
'Manhattan Mansion',
'In the heart of New York City',
'http://www.boweryboyshistory.com/wp-content/uploads/2008/08/top1.jpg',
149.9,
new Date('2019-01-01'),
new Date('2019-12-31'),
'dima')]);
get places() {
return this._places.asObservable();
}
}
export class DiscoverPage implements OnInit, OnDestroy {
loadedPlaces: Place[];
placesSubscription: Subscription;
constructor(private placeService: PlacesService) {}
ngOnInit() {
console.log('DiscoverPage: ngOnInit');
this.placesSubscription = this.placeService.places.subscribe(places => this.loadedPlaces = places);
}
ngOnDestroy() {
console.log('ngOnDestroy');
this.placesSubscription.unsubscribe();
}
我可以删除placesSubscription
并期望由于我订阅的对象类型为Observable
而自动取消订阅吗?
答案 0 :(得分:2)
具有无限序列时,例如,在使用interval()或fromEvent()可观察对象时,应该取消订阅(除非有特殊情况)。
请勿退订:
异步管道
@Component({
selector: 'test',
template: `<todos [todos]="todos$ | async"></todos>`
})
export class TestComponent {
constructor(private store: Store) { }
ngOnInit() {
this.todos$ = this.store.select('todos');
}
}
@HostListener
export class TestDirective {
@HostListener('click')
onClick() {
....
}
}
有限可观察
export class TestComponent {
constructor(private http: Http) { }
ngOnInit() {
Observable.timer(1000).subscribe(console.log);
this.http.get('http://api.com').subscribe(console.log);
}
}
更多信息:
https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87
https://netbasal.com/when-to-unsubscribe-in-angular-d61c6b21bad3
答案 1 :(得分:1)
您应该取消订阅。
Angular不会自动取消订阅您自己创建的可观测对象。