在 html 中显示来自 json Angular 中的 http 服务的数据

Display data in the html coming from http service in json Angular

我想得到一些帮助来解决这个简单的问题。

我收到 API returns 我的以下消息:

[
  "{\"name\":\"testing\",\"desc\":\"test\",\"other\":\"search\"}",
  "{\"name\":\"test\",\"des\":\"testing\",\"other\":\"search\"}"
]

我正在使用这个模型:

export class myModel {
    name: string;
    desc?: string;
    other: string;
}

我正在使用以下服务正确接收消息:

  private emitList$ = new Subject<myModel[]>();
  private listObserver$: Observable<myModel[]> = this.emitList$.asObservable();

  public getting() {
    this.http.get<myModel[]>(this.URI_ENDPOINT_GET_URI, this.httpheaders)
    .pipe(
      catchError(this.handleError)
    )
    .subscribe(list=> {
      this.emitList$.next(list);
    });
  }

  public getListObserver(): Observable<myModel[]> {
    return this.listObserver$;
  }

这是使用以下代码从我的打字稿视图代码中调用的:

  constructor(private myService: MyService,
              private changeDetectorRefs: ChangeDetectorRef ) {
              }

  dataModel: myModel[];
  this.listSubscription= this.myService.getSchedulingObserver();

    this.listSubscription.subscribe(lists=> {

      this.dataModel = lists;

      console.log("LISTS")
      console.log(lists)
      console.log("DATAMODEL")
      console.log(this.dataModel)
    });

加上console.log,结果如下:

    LISTS
(2) ["{"name":"testing","desc":"test","other":"search"}", "{"name":"test","desc":"testing","other":"search"}"]
DATAMODEL
(2) ["{"name":"testing","desc":"test","other":"search"}", "{"name":"test","desc":"testing","other":"search"}"]

最后在 html 代码中,我尝试使用 NgFor 获取变量,但没有绘制值,控制台中也没有错误。然而,数据变量(第一个字段)在网站上正确绘制为以下格式,并在 ngFor 上迭代两次:

{"name":"testing","desc":"test","other":"search"}

我认为 array/json 的格式存在某种我没有意识到的问题。

<mat-card>
  <ul>
    <li *ngFor="let data of dataModel">
      {{ data }}
      <p>DATA SLICED</p>
      {{ data.name}}
      {{ data.desc}}
      {{ data.other}}
      <p>END</p>
    </li>
  </ul>
</mat-card>

由于 API returns 数据为字符串,因此需要将其转换为 JSON 格式。


this.dataModel.forEach((data, i) => {
  this.dataModel[i] = JSON.parse(data);
})

...................................

<mat-card>
  <ul>
    <li *ngFor="let data of dataModel">
      {{ data|json }}
      <p>DATA SLICED</p>
      {{ data.name}}
      {{ data.desc}}
      {{ data.other}}
      <p>END</p>
    </li>
  </ul>
</mat-card>