Angular 6-http get请求响应映射到对象

时间:2019-02-22 12:31:56

标签: angular class http dictionary request

我有一个JSON文件,尝试通过获取http请求加载并映射 模型类。

我有JSON文件

[
  {
    "firstName": "Dan1",
    "lastName": "Dan1"
  },
  {
    "firstName": "Dan2",
    "lastName": "Dan2"
  },
  {
    "firstName": "Dan3",
    "lastName": "Dan4"
  }
]

我有这样的模型代码:

export class Record {
  firstName: string;
  lastName: string;
}

以及类似的组件:

import {Component} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Record} from './models/record';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'CRM';
  apiUrl = './assets/test.json';
  itemList: Array<Record>;

  constructor(private http: HttpClient) {

    const obs = this.http.get<Record[]>(this.apiUrl, {responseType: 'json'});
    obs.subscribe((records: Record[]) => {
      this.itemList = records;
    });

  }
}

问题:

  1. 为什么 this.itemList 不是记录数组,尽管我使用的是this.http.get<Record[]>(records: Record[])。这是否意味着Angular不会在记录数组上映射JSON?如果是,这些定义是什么?

  2. 有什么方法可以执行此操作而无需手动创建此对象并将其放入数组?

2 个答案:

答案 0 :(得分:0)

itemList不是Record的数组,因为TypeScript基本上是具有用于编译器类型的javascript。编译器只是检查。如果您说http.get返回了Record[],则编译器认为您返回的对象将具有该结构。

由您决定是否将其实际设置为Record数组。这很容易,并且需要手动完成,就像在JavaScript中一样:

obs.pipe(
  map((records) => records.map((record) => Object.assign(new Record(), record)))
).subscribe((records: Record[]) => {
  this.itemList = records;
});

不过,请咨询async管道。这样,您就不必在组件内部进行订阅,而且看起来整洁了一点。

答案 1 :(得分:0)

您可以执行以下操作:

this.itemList = records.map(r => Object.create(new Record(), r);

为什么呢?因为我猜。