【问题标题】:Angular 2 : Modified import Model don't update in viewAngular 2:修改后的导入模型不在视图中更新
【发布时间】:2017-05-16 20:29:40
【问题描述】:

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

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,但没有任何效果。

提前感谢您的帮助!

【问题讨论】:

  • 这是区分大小写的...您正在接收数据,例如id。它与Id 不是同一个属性。
  • 是的,我知道,但这就是我要问的原因。更改模型不会更改我视图中的数据@AJT_82
  • 是的,这是预期的行为。在接收数据时,您必须做的是将值映射到您的新属性名称:)
  • 怎么做? @AJT_82

标签: html angular view angular2-template


【解决方案1】:

我建议您使用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 类型的数组。

【讨论】:

  • 好的,请告诉我进展如何。这让我想了想,也许你的数组中总是有一个 CV,然后我们可以稍微改变一下代码,这样你就不会得到一个包含一个对象的数组,但是我们可以只映射那个对象,但是让我知道,如果是这样的话,我会做出适当的改变! :)
  • 遗憾的是不起作用:编译器不理解这部分:Id:x.id(这是正常的,因为我的 ts 模型与 C# 完全相同)
  • 我不明白。您的模型属性中有大写字母...例如Id,但在 JSON 中您收到的是小写字母 id?这就是我使用Id:x.id 的原因。
  • 错误是:“CV”类型中不存在属性“id”
  • 我尝试了其他实体,例如专业知识:this.http.get(this.actionUrl, this.CVSelection.getCV().Id).map((response: Response) =&gt; &lt;Expertise[]&gt;response.json().map((x: Expertise) =&gt; Object.assign({ Id: x.Id, Name: x.Name })))
猜你喜欢
  • 2016-08-23
  • 2017-09-07
  • 2021-05-21
  • 2019-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
相关资源
最近更新 更多