[英]Wait for subscription to finish in angular 8
我有一个组件,我在 onInit 中调用区间内的订阅:
ngOnInit() {
interval(5000).pipe(
takeWhile(() => this.isAlive))
.subscribe(() => {
this.initialization();
});
}
initialization() {
this.subscriptions.add(
this.someService.someMethod().subscribe(
data => {
this.myData = Object.assign({}, data);
this.var1 = this.myData.x; // Using var1 in HTML to bind to a text element
this.var2 = this.myData.y; // Using var2 in HTML to bind to a text element
}
)
);
}
var1Change(value) {
// Check if my code is in observable, once it is finish, execute save immediately. How to acheive it?
this.var1 = value;
this.myData.x = value;
this.callSave();
}
callSave() {
// Method to consume api to save data to file
}
因此,每当数据有更新时,我的 UI 就会每 5 秒更新一次。
我可以从 UI 进行更改并通过使用 API 将数据保存到文件中,并且在模型更改时发生保存,然后只发生保存。 它没有保存按钮。
所以我想要什么如果我的代码在可观察范围内,我想等待保存发生
请帮助我使用现有代码,因为我必须以这种方式使用间隔和保存调用
使用 angular 8.2 和 rxjs 6.4
我的理解是,如果更新正在进行中,您希望在保存之前等待。 如果是这种情况,那么您可以执行以下操作。
updateSubject = new Subject<any>(); //subject to notify when update completes
saveSubject = new Subject<any>(); //subject to save data
updateInProgress = false; //indicates whether the update is under progress
constructor() {
this.updateSubject.subscribe(() => this.updateInProgress = false);
}
ngOnInit() {
interval(5000).pipe(
takeWhile(() => this.isAlive))
.pipe(tap(()=> this.updateInProgress(true))) //mark updateInProgress
.subscribe(() => {
this.initialization();
});
}
initialization() {
this.subscriptions.add(
this.someService.someMethod().subscribe(
data => {
this.myData = Object.assign({}, data);
this.var1 = this.myData.x; // Using var1 in HTML to bind to a text element
this.var2 = this.myData.y; // Using var2 in HTML to bind to a text element
this.updateSubject.next(); //when update completes we emit
}
)
);
}
var1Change(value) {
if(!this.updateInProgress) {
this.callSave();
} else {
// we forkjoin both save & update subject so when both emits then only save will happen
forkjoin(this.saveSubject.pipe(take(1)),this.updateSubject.pipe(take(1))).subscribe(() => {
this.callSave();
}
this.saveSubject.next();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.