猿问

在执行另一个可观察对象之前等待一个可观察对象检索数据

我有这两个 http 调用:


const newProject = this.newProjectForm.value;

newProject.stage = "In progress";


let newProjectFromServer: IProject;


this.projectService.addProject(newProject).subscribe((data) => {

  newProjectFromServer = data;

});


this.projectService

  .addEmployeesToProject(

    newProjectFromServer.id,

    newProject.assignedEmployees

   )

   .subscribe(() => {

     this.afterSubmit();

   });


第一个将项目添加到数据库中,因此 Spring 对其应用了一个 id,因此在我作为响应获得的数据中,它现在应该有一个 id。然后我尝试添加从表单中获得的指定员工数组。问题是 newProjectFromServer.id 参数未定义,因为我认为它是同步读取的


编辑:这是 addEmployeesToProject 函数:


addEmployeesToProject(

    projectId: number,

    employees: IEmployee[]

  ): Observable<IEmployee[]> {

    return this.httpClient.post<IEmployee[]>(

      `${this.baseUrl}/${projectId}/employees`,

      {

        _embedded: { employees },

      }

    );

  }

Api 结果:


{

"_embedded": {

     "employees": [] // IEmployee[] array doesnt get save

   },

   "_links": {

     "self": {

      "href": "http://localhost:8080/api/projects/26/employees"

     }

   }

 }

添加项目请求:


addProject(project: IProject): Observable<IProject> {

    return this.httpClient.post<IProject>(this.baseUrl, project);

  }


幕布斯7119047
浏览 110回答 3
3回答

Helenr

像这样的东西应该使用 switchMap 运算符this.projectService.addProject(newProject).pipe(&nbsp; tap(data => newProjectFromServer = data),&nbsp; switchMap(() => {&nbsp; &nbsp; return this.projectService.addEmployeesToProject(&nbsp; &nbsp; newProjectFromServer.id,&nbsp;&nbsp; &nbsp; newProject.assignedEmployees&nbsp; )}).subscribe((secondResult) => {&nbsp; &nbsp;this.afterSubmit()});我希望它有所帮助。有关 switchMap 运算符的研究链接:https://www.learnrxjs.io/learn-rxjs/operators/transformation/switchmap

Smart猫小萌

您可以使用concatMap、switchMap、mergeMap。建议使用concatMap,因为它可以确保 HTTP 调用的顺序执行。this.projectService.addProject(newProject).pipe(&nbsp; concatMap((newProjectFromServer) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; this.projectService.addEmployeesToProject(&nbsp; &nbsp; &nbsp; &nbsp;newProjectFromServer.id,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;newProject.assignedEmployees&nbsp; &nbsp; )}).subscribe((secondResult) => {&nbsp; &nbsp;this.afterSubmit()});

蝴蝶刀刀

我认为更好的方法是将其转换为承诺:public async myFunc(): Promise<void> {const newProjectFromServer = await this.projectService.addProject(newProject).toPromise()await this.projectService&nbsp; .addEmployeesToProject(&nbsp; &nbsp; newProjectFromServer.id,&nbsp; &nbsp; newProject.assignedEmployees&nbsp; &nbsp;).toPromise();this.afterSubmit();}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答