Malik Kashmiri Malik Kashmiri - 2 months ago 18
TypeScript Question

Undefined while cast api response in any type in angular 2

I want to store data like this

public initData: any = ['Group 1', 'Group 2', 'Group 3'];
.
I am calling an API and It gives this response
Image

I declare
private initData: any;
and after getting the response I try to store in that like this

this.userService.getUserRolesById(this.id)
.subscribe(data => {
this.initData = data.Name;
console.log(this.initData);
})


userservice



public getUserRolesById(id: number) {
return this.httpHelper.get(this._getUserRolesByIdUrl+'?userId='+id)
.map(res => res.json());
}

Answer

The problem here is that you get an array and you want a property in this array.

public initData:string[] = [];//Typing your arrays is important ;).
...
...
...
this.userService.getUserRolesById(this.id)
    .subscribe(roles => {
        roles.forEach(role => {
            console.log(role.Name);
            this.initData.push(role.Name);
        }
});
Comments