Arash EM
Arash EM

Reputation: 380

why doesn't mapping data from web API work in Angular 2

I am new to Angular 2. I am trying to get some data from a web api and I can see the data are populated correctly after angular 2 call. My problem is the mapping doesn't work as I expected.

In my Angular service I have:

getEmployees() {
    return this._http.get(this._employeeUrl)
        .map(res => <Employee[]>res.json())
        .catch(this.handleError);
}

In my angular component I have:

   public EmployeeList : Employee[];

    getEmployees() {
        this._employeeService.getEmployees()
            .subscribe(
            value => {
                this.EmployeeList = value
            },
            error => this.errorMessage = <any>error);
    }

and

export interface Employee{
    Id: number,
    FirstName: string,
    Phone: string
}

When I am debugging I can see it pulls the data from web api, something like:

Object {id: 10, firstName: "Arash", phone: "11212121"}

but it doesn't convert the object to EmployeeList, i.e. when I try to do something like EmployeeList.FirstName, it says it's undefined. I noticed that if I defined EmployeeList like:

public EmployeeList = [];

The result is the same, so I am thinking the mapping doesn't work as I expected.

Can anyone help how to fix the issue.

Upvotes: 0

Views: 107

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657376

Casting to an interface is only information for your tools that do static analysis of your code. It doesn't change the behavior of your application. Interfaces are just dropped at runtime.

You should create a class that implements that interface like

class MyEmployee implements Employee {
  constructor(public Id:number, public Firstname:string, publich Phone:string){}
}

and use it like

.map(res => res.json.map(e => new MyEmployee(e.id, e.firstName, e.phone))

Upvotes: 2

Related Questions