我有一个http呼叫,看起来像这样:

public getCommuneByCode(code: string): Observable<Commune> {
  return this.http.get<Commune[]>(ApiUrl);
}


和公社模型如下:

export interface Commune {
  code: string;
  departement: string;
  postalCode: string;
}


我还有另一个http调用来获取用户数据:

public getUserData(id: number): Observable<User> {
  return this.http.get<User>(ApiUrl);
}


用户模型:

export interface User {
  id: number;
  name: string;
  libAddress: string;
}


我想要做的是使用getCommuneByCode服务的响应来设置libAddress属性,如下所示:

this.service.getUserData(id).pipe(
    map((user: User) => {
      user.libAddress = this.service.getCommuneByCode(code).pipe(
        map(commune => `${commune.postalCode} - ${commune.departement}`)
      );
      return user;
    })
  ).subscribe((userWithLibAddress) => {
    // user object with all data and libAddress property is equal to ex: 99999 - DepartementXX
  })


但是正如我期望的那样,它返回的是可观察到的答案,而且我不确定如何获得答案。感谢您的帮助

最佳答案

这应该工作。如果您需要解释,请提出要求!

forkJoin(
  this.service.getUserData(id),
  this.service.getCommuneByCode(code)
).pipe(
  map(([user, commune]) => ({ ...user, libAdress: `${commune.postalCode} - ${commune.departement}`})
);


编辑如果您必须按顺序进行呼叫:

this.service.getUserData(id).pipe(
  switchMap(user => this.service.getCommuneByCode(user.code)).pipe(
    map(commune => ({ ...user, libAdress: `${commune.postalCode} - ${commune.departement}`}))
  )
)

10-06 04:05