Angular observable,如何遍历具有嵌套数组的对象以将字段收集到数组中

Angular observable, how to iterate through an object with nested array to collect fields into an array

我正在尝试遍历我的 JSON 对象并将特定字段添加到它们自己的数组中。

我正在尝试遍历以下对象并将 'appSupportedId' 存储在它自己的数组中。

我遇到错误

错误

 core.js:15714 ERROR TypeError: info.flatMap is not a function

我在我的代码中实现了类似的东西,但与后端 json 对象的唯一区别是下面的对象有一个嵌套数组

如有任何帮助,我们将不胜感激!

component.ts

userAppDetails:[];

this.incidentService.get(this.id)
  .subscribe((info) => 
    this.userAppDetails = (info.flatMap(x => x.applicationsSupported)).contactAll().map(y=> y.appSupportedId))

JSON 对象

 "incidentNumber": 18817,
 "Email": null,
 "applicationsSupported": [
    {
        "appSupportedId": 18569,           
        "supportAreaId": 122,
        "supportAreas": {
            "applicationId": 122,               
            "activeFlag": "Y",
        },
        "appSupportedName": "app 1"
    },
    {
        "appSupportedId": 18592,          
        "supportAreaId": 123,
        "supportAreas": {
            "applicationId": 123,
            "activeFlag": "Y",
        },
        "appSupportedName": "app 2"
    },
    {
        "appSupportedId": 18655,
        "supportAreaId": 122,
        "supportAreas": {
            "applicationId": 122,
            "activeFlag": "Y",
        },
        "appSupportedName": "app 3"
    }
],
"createdDate": "2020-01-17T18:02:51.000+0000",

您似乎混淆了可观察的管道运算符(在订阅之前的管道内)和对象运算符(在订阅内)。

RxJS 管道运算符在可观察流中工作,它们非常强大。您甚至可以在订阅之前将一堆操作员放在一起。有时您可以在订阅中获得类似的结果,尽管这通常会导致代码混乱。

flatMap

concatAll

以下(https://stackblitz.com/edit/rxjs-d9nchy)是一个使用map RxJS操作符的例子。注意这与数组映射运算符不同:

import { of } from 'rxjs'; 
import { map } from 'rxjs/operators';

const DATA = {
  "incidentNumber": 18817,
  "Email": null,
  "applicationsSupported": [
      {
          "appSupportedId": 18569,           
          "supportAreaId": 122,
          "supportAreas": {
              "applicationId": 122,               
              "activeFlag": "Y",
          },
          "appSupportedName": "app 1"
      },
      {
          "appSupportedId": 18592,          
          "supportAreaId": 123,
          "supportAreas": {
              "applicationId": 123,
              "activeFlag": "Y",
          },
          "appSupportedName": "app 2"
      },
      {
          "appSupportedId": 18655,
          "supportAreaId": 122,
          "supportAreas": {
              "applicationId": 122,
              "activeFlag": "Y",
          },
          "appSupportedName": "app 3"
      }
  ],
  "createdDate": "2020-01-17T18:02:51.000+0000",
}
const source = of(DATA).pipe(
  map(x => x.applicationsSupported),
  map(arr => arr.map(entry => entry.appSupportedId))
);

source.subscribe(x => console.log(x));