Angular 2:修改后的导入模型不会在视图中更新

问题描述 投票:0回答:1

我更改了模型以适应使用实体框架的要求,但与该模型相关的视图无法使用新模型:

export class CV {
    public Id: number;
    public UserId: string;
    public Context: string;
    public Competences: Array<Competence>;
    public Expertises: Array<Expertise>;
    public Formations: Array<Formation>;
    public Missions: Array<Mission>;
}

变更前的型号为:

export class CV {
    public id: number;
    public userId: string;
    public context: string;
    public competences: Array<Competence>;
    public expertises: Array<Expertise>;
    public formations: Array<Formation>;
    public missions: Array<Mission>;

例如,我从控制台显示一个对象: Screenshot from my Chrome console

所以我想更新我认为的模型,但我不知道如何做。我尝试了不同的方法,例如 ChangeDetectorRef 但没有任何效果。

提前感谢您的帮助!

html angular view angular2-template
1个回答
0
投票

我建议您使用

Interfaces
而不是类,因为在查看模型时,您不需要类。因此将其更改为接口:

export interface CV {
    Id: number;
    UserId: string;
    Context: string;
    Competences: Array<Competence>;
    Expertises: Array<Expertise>;
    Formations: Array<Formation>;
    Missions: Array<Mission>;
}

由于您的属性名称与您接收的数据不匹配,因此您需要映射值并使用与您的模型匹配的属性设置数据。

所以你的服务函数应该是这样的:

getData() {
  return this.http.get('the url')
    .map(res => res.json().map((x:any) => 
      Object.assign({Id:x.id,UserId:x.userId,/* Rest of the properties here */})))
}

然后在您的组件中正常订阅并将传入数据分配为

CV
类型的数组。

© www.soinside.com 2019 - 2024. All rights reserved.