本文介绍了Angular 5-两个不同组件中的异步服务调用(第一种方法不等待数据库响应)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在一个(单击)事件上执行两个不同的数据库事务.

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.

我需要对保存"方法的服务调用应等待数据库响应,然后继续执行其他组件中的获取"方法.

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);
  }
}

在第二个组件中,订阅服务的数据$可观察:

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-两个不同组件中的异步服务调用(第一种方法不等待数据库响应)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:26