0

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.

0

1 Answer 1

2

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))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply. I will give it a go and see the result, but would like to know if there is any other way to automatically map the object without using constructor. My concern is for objects with lots of members. I don't want to map them one by one.
You can ensure that the data sent by the server matches the interface or that the interface matches the actual received data, then just casting will do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.