正在 Angular 中的对象中获取对象

Fetching object in object in Angular

我正在尝试从我的后端获取数据 API,但我不知道如何获取另一个对象中的对象。

这是我后端的响应:

{
    "id": 4,
    "website_id": 1,
    "user_id": 5,
    "username": "Swarton3"
},
{
    "id": 5,
    "website_id": 1,
    "user_id": 5,
    "username": "Test123"
}

website_id 属性 中,我想从另一个端点获取有关该网站的 return 信息的数据。

所以最后的事情应该是这样的:

{
    "id": 4,
    "website": {
        "id": 2,
        "name": "Test2",
        "url": "test2.com"
    },
    "user_id": 5,
    "username": "Swarton3"
},
{
    "id": 5,
    "website": {
        "id": 1,
        "name": "Test",
        "url": "test.com"
    },
    "user_id": 5,
    "username": "Test123"
}

在服务中做到这一点的最佳方法是什么?应该在我的后端获取所有数据吗?

首先,我的建议是重新考虑您的 API。因为如果您的响应中有很多对象,您最终会收到过多的 http 请求。
否则,您可以结合使用 RxJS switchMap 和 forkJoin 运算符。

// assuming you have have two methods in your service
// yourService.fetchRecords to fetch the first level data,
// yourService.fetchWebsite to fetch the website by its website_id.
// then the method which return the full data would be like below:
fetchFullData(): YourData {
  this.yourService.fetchRecords().pipe(
    switchMap((records) => {
      const websiteRequests = records.map(record => this.yourService.fetchWebsite(record.website_id));
      return forkJoin(websiteRequests).pipe(
        map((websites) => records.map((record, idx) => ({
          id: record.id,
          user_id: record.user_id,
          username: record.username,
          website: websites[idx]
        })))
      );
    })
  )
}

说明: switchMap 用于将外部 observable 映射到内部 observable。在您的情况下,外部可观察对象是由 this.yourService.fetchRecords() 创建的。内部可观察对象是由 forkJoin 函数创建的。 forkJoin 接受一组可观察对象和 returns 一个仅在所有接受的可观察对象完成后才发出的单个可观察对象。因此,对于由 yourService.fetchWebsite() 创建的可观察对象,它只会在获取所有相应网站时发出。