Angular 5 - 两个不同组件中的异步服务调用(第一种方法不等待数据库响应) [英] Angular 5 - Asynchronous Service Calls in two different components (First Method Not waiting for DB response)
问题描述
我必须对单个(点击)事件执行两个不同的数据库事务.
I have to perform two different DB transactions on a single (click) event.
第一次调用:将数据保存到数据库.
First Call : Save Data to DB.
第二次调用:从数据库中获取第一次调用的保存数据
Second Call : Get the first call's saved data from DB
这些调用分为两个不同的组件,并处理一个公共数据库表.
These calls are separated in two different components and deal with one common DB Table.
我的方法如下:
第一个组件 TS :
ngOnDestroy(){ this.saveData(); }
第二个组件 TS :
ngOnInit(){ this.getSavedData(); }
第一个执行方法的服务调用:
saveData(obj) {
return this.http.post(environment.appUrl + 'saveDataApi', obj).toPromise()
.then(res => <any>res); }
这两种方法都是按编码顺序触发的.但我的问题是 this.getSavedData();
在 Save 方法的数据库事务完成之前完成了它的数据库事务&返回响应.
Both these methods are getting triggered sequentially as coded. But my issue is that this.getSavedData();
completes its DB transaction earlier before Save method's DB transaction is completed & response is returned.
我需要'Save'方法的服务调用应该等待数据库响应,然后在其他组件中继续'Get'方法.
I need that the service call for 'Save' method should wait for DB response and then proceed to 'Get' method in other component.
简而言之:this.getSavedData();
不应该被执行,除非this.SaveData();
完成它的整个执行返回响应.
In short : this.getSavedData();
should not be executed until and unless this.SaveData();
completes its entire execution returning a response.
我错过了什么?
推荐答案
创建一个名为 data.service.ts
(名称随意)的服务来处理 HTTP 调用.制作一个 saveData
方法.从第一个组件调用它(尽管我不确定 ngOnDestroy 是否是进行此类调用的最佳位置):
Create a service called data.service.ts
(name as you wish) to handle the HTTP call. Make a saveData
method. Call that from the first component (although I'm not sure if ngOnDestroy is the best place to make a call like that):
ngOnDestroy(){ this.dataService.saveData(); }
以响应成功时从服务发出结果的方式实现您的服务:
Implement your service in a way that it emits the result from the service when the response suceeded:
@Injectable()
export class DataService {
private _data$ = new ReplaySubject(1);
public data$ = this._data$.asObservable();
saveData(obj) {
return this.http.post(environment.appUrl + 'saveDataApi', obj).pipe(
tap(res => this._data$.next(res)
)
.toPromise()
.then(res => <any>res);
}
}
在您的第二个组件中,订阅服务的 data$ Observable:
In your second component, subscribe to the service's data$ Observable:
ngOnInit() {
this.dataSubscription = this.dataService.data$.subscribe(() => [..])
}
并且不要忘记在离开组件时取消订阅:
And don't forget to unsubscribe when you leave the component:
ngOnDestroy() {
this.dataSubscription.unsubscribe();
}
Or bind data$ to your template directly using the async pipe.
Maybe you should consider adding a state management framework to your application, like ngRX, but that is a bigger jump.
这篇关于Angular 5 - 两个不同组件中的异步服务调用(第一种方法不等待数据库响应)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!