Search code examples
htmlangularviewangular2-template

Angular 2 : Modified import Model doesn't update in view


I changed my model to fit requirements for using entityframework but the view related to this model can't use the new model which is:

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>;
}

The model before changing is:

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>;

Example, I show an object from my console: Screenshot from my Chrome console

So I want to update the model in my view but I don't know how. I tried different things like ChangeDetectorRef but nothing is working.

Thank you in advance for your help!


Solution

  • I'd suggest you'd use Interfaces instead of classes, since at looking at the model, you don't need a class. So change it to an interface instead:

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

    Since your property names do not match the data you are receiving, you need to map the values and set the data with the properties that match your model.

    So your service function should look something like this:

    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 */})))
    }
    

    And then in your component you subscribe normally and assign the incoming data as an array of type CV.