0

我有一个界面

export interface Shelving {
  _id?: string,
  name: string,
  location: string,
  comment: string,
  catID: string,
  catName: string
}

从服务中,我从服务器获取数据

  fetch(): Observable<Shelving[]> {
    return this.http.get<Shelving[]>('api/shelving')
  }

来自服务器的对象

{
  "_id": "5ec3edbab1565f5d671c201e",
  "name": "89",
  "comment": "",
  "catID": "",
  "catName": "5ec3ed79b1565f5d671c201c",
  "location": "5ec3eccef1d51c3a48bd722e",
  "__v": 0,
  "categoryName": [    <-------------- object
    {
      "_id": "5ec3ed79b1565f5d671c201c",
      "catName": "test category name",  <------------------ name I needed
      "comment": "",
      "__v": 0
    }
  ],
  "locationObj": [
    {
      "_id": "5ec3eccef1d51c3a48bd722e",
      "name": "yyy",
      "phone": "+2310232309",
      "comment": "",
      "address": "EGNATIA 156",
      "__v": 0
    }
  ]
}

问题是: 如何将类别名称从对象推送到数组? 我想在 html 组件中打印一个值。像这样的东西: {{ shelving.catName }} 但现在我打印这样:

<td>{{ shelving.categoryName[0].catName }}</td>

我觉得这不是真正的方式-_-

4

1 回答 1

0

我可能误解了这个问题。如果这是您想要的,我可以告诉您一种将值传递到模板的方法:

catNames$: Observable<Shelving[]> = this.http.get<Shelving[]>('api/shelving').pipe(
          map(({ categoryName }) => categoryName.map(cat => cat.catName)),
          shareReplay(1)
       );

在 html 上:

<td>{{ catNames$ | async }}</td>

所有这一切都是将来自服务器的值映射到您想要的形状,然后通过async管道将这些值绑定到模板。这shareReplay(1)是为了确保每次更改检测运行时都不会命中 http 端点。

这里需要注意的是,您必须在界面categoryName上添加为属性。Shelving

于 2020-05-20T04:00:13.953 回答