首页 > 解决方案 > 如何在一系列 API 调用中正确链接 observables

问题描述

我有几个相互依赖的 API 调用。具体来说,我无法让最终的 Observable 正确返回:它会导致应用程序无限期地滞后。

如果我this.projectAttributeService.findAndUpdateByProjectAndMetumId({...})自己打电话然后打电话.subscribe给它,它似乎工作正常。这表明我在前端的 Observable 链接存在问题。就目前而言,甚至没有在后端调用该方法(我设置了断点)。

// 。服务

submitPhasesForm(projectId) {
  return this.activityDateService.activities$.pipe(
    first(),
    concatMap((activities: ActivityDate[]) => {
      this.activities = activities;
      if (this.activities.length === 0) {
        return observableOf({});
      }
      this.activities = activities.map(a => {
        a.project_program_id = parseInt(projectId, 10);
        return a;
      });
      return this.activityDateService.update(this.activities);
    }),
    mergeMap(() => {
      if (this.activities.length === 0) {
        return observableOf({});
      }
      return this.projectAttributeService.getAllMetadata(3).pipe(first())
    }),
    mergeMap((metaData: ProjectAttMetadataAPIResponse) => {
      if (this.activities.length === 0) {
        return observableOf({});
      }
      const metaDataId = (metaData as any).find(m => m.name === 'Phase').id;

    // EDIT: the problem ended up being with the synchronous 
    // this.getProjectPhase(this.activities) method below
      return this.projectAttributeService.findAndUpdateByProjectAndMetumId({
        project_program_id: parseInt(projectId, 10),
        value: this.getProjectPhase(this.activities),
        project_attrib_metum_id: metaDataId
      })
    })
  )
}

findAndUpdateByProjectAndMetumId()看起来是这样的(调用本身似乎可以正常工作):

findAndUpdateByProjectAndMetumId(body: ProjectAttribute): Observable < ProjectAttribute > {
  return this.http.put < ProjectAttribute > (`${ environment.API_URL }project-attribute`, body);
}

这就是submitPhasesForm()被调用的地方:

// 。零件

import { forkJoin as observableForkJoin } from 'rxjs';

return this.projectService.patch(this.projectId, {
    summary: projectSummary || proj.summary
  }).pipe(
    first(),
    mergeMap(() => {
      return observableForkJoin(
        this.phasesFormDataService.submitPhasesForm(this.projectId).pipe(first()),
        this.pdpMetricsFormService.submitPdpForm(this.projectId).pipe(first()),
        this.projectStatusFormService.submitStatusForm(this.projectId).pipe(first())
      )
    })
  )
  .subscribe((res) => {
    this.router.navigate([`./pdp/${this.currentTab}/${this.projectId}`]);
  });

其他两个调用非常相似,尽管更短:

submitPdpForm(projectId) {
    return this.pdpMetricsForm$.pipe(
      first(),
      concatMap((formGroup: FormGroup) => {
        if (!formGroup.get('etRadioModel')) {
          return observableOf({});
        }

        const objSend = {...}
        return this.projectService.upsertPdpMetrics(projectId, objSend);
      })
    )
  }

...

submitStatusForm(projectId) {
    return this.metrics$.pipe(
      first(),
      tap(metrics => {
        this.metricsData = metrics;
      }),
      mergeMap(() => this.statusesForm$),
      observableMap(statusesForm => {
        const formGroup = statusesForm;

        if (!formGroup.get('resourceRationale')) {
          return {};
        }

        const obj = [{...}]

        return sendObj;
      }),
      mergeMap((sendObj: any) => {
        if (isEmpty(sendObj)) { return observableOf(sendObj) };
        return this.projectService.upsertMetrics(projectId, sendObj).pipe(first());
      })
    )

我链接或调用这些 Observable 的方式有什么不妥之处吗?

任何帮助深表感谢!

of({})如果第一个Observable 没有产生数据,我将返回activities$,这样我就可以通过 Observable 流而无需进行不必要的 API 调用——我愿意接受有关更流畅break的 Observable 链的建议。

标签: angulartypescriptrxjsreactive-programming

解决方案


原来我的同步this.getProjectPhase(this.activities)方法有一个逻辑错误,将应用程序发送到无限循环。

否则,Observable 操作符可以正常工作。

this.activities如果是空的,我仍然想找到一种更时尚的方式来摆脱那个流。


推荐阅读