所以我的应用程序有一个弹出窗口,它有一个forkjoin observable,如果用户选择了很多项,可能需要很长时间才能运行。如果用户在此过程中关闭窗口,则应用程序将处于静止状态,直到forkjoin完成执行,并且在我的主应用程序中没有任何工作。我通过使用订阅取消订阅forkjoin但它仍然运行直到它完成。这是我的代码:
subscriptions: Subscription[] = [];
ngOnDestroy() {
// prevent memory leak when component destroyed
this.subscriptions.forEach(s => s.unsubscribe());
}
//get all my items
getItems() {
//set item list to blank
this.itemList = [];
let observables = [];
this.loadItems = true;
//get sections that user selected
this.subscriptions.push(
this.organizationService.GetSelectedSections(this.sectionID, this.culture)
.subscribe(
(selectedSections: GetSelectedSections[]) => {
this.selectedSectionsAll = selectedSections;
//push all selected sections in observables
for (let section in selectedSections) {
observables.push(this.organizationService.GetItemsBySection( selectedSections[section].sectionItemID, this.culture));
}
// get all items in sections to display
if (observables.length != 0) {
this.subscriptions.push(
Observable.forkJoin(observables)
.subscribe(
(result: any) => {
this.itemList = result;
},
(error: any) => {
this.errorMessage = error
this.loadItems = false;
},
() => {
this.loadItems = false;
}
)
);
}
},
(error: any) => {
this.errorMessage = error
},
() => {
}
)
);
}
答案 0 :(得分:0)
随着时间的推移,我已经了解到正确清理您的可观测量只是一种很好的做法。通常,在我的ngDestroy中,我有:
ngOnDestroy() {
this.updateService.clearUpdate(); //this is where I call the next() method
//on the observable to clear it
this.subscription.unsubscribe(); //I call this directly on the Subscription object
//To clear obviously unsubscribe
this.alive = false; //I use this in the subscribed method in my component
//as a boolean for the rxjs takeWhile() method...
}
我的一个典型的pub / subs
this.updateService.getUpdate()
.takeWhile(() => this.alive)
.subscribe(message => {...impl...}
我的消息传递结构总是在组件类外部,非常简单
public message = new Subject<any>();
constructor(private zone: NgZone) {
}
sendUpdate(message) {
this.zone.run(() => {
this.message.next(message);
});
}
getUpdate(): Observable<any> {
this.zone.run(() => {
this.message.asObservable();
});
return this.message.asObservable();
}
clearUpdate() {
this.zone.run(() => {
this.message.next();
});
}
我尽可能保持简单。我也使用angular的区域()来确保UI的更新,无论何种类型的环境。希望这会有所帮助..