Reputation: 155
I have a situation where i need to push the response of an API called to an array. Previously, I hard coded the data like this.
filterrole = [
{ text: 'Supervisor', value: 'Supervisor' },
{ text: 'Administrator', value: 'Administrator'},
{ text: 'Maintainer', value: 'Maintainer' }
];
But now, i need to get the data from the backend. The backend query is fine. this is how the result looks like from the backend called.
["Supervisor","Maintainer","Observer","Administrator"]
the filterrole has it own class which consist of text and value variable.
Role.class
export class Role {
text: string;
value: string;
}
My question is, how do I push the response from the API call into the filterrole variable ? Below is my workaroud.
export class AddGroupComponent implements OnInit {
filterrole: Role [];
ngOnInit() {
this.getDistinctRole();
}
getDistinctRole(): void {
this._dashboardservice.getDistinctRole().subscribe(
resp => {
// what should i do here to push the data into
// filterdata.text and filterdata.value
},
err => {
this.loading = false;
this._nzMessage.create('error', `Error occurred: ${err.message}`);
}
);
}
Upvotes: 1
Views: 3072
Reputation: 378
you can do like this as well
export class AddGroupComponent implements OnInit {
filterrole = [];
ngOnInit() {
this.getDistinctRole();
}
getDistinctRole(): void {
this._dashboardservice.getDistinctRole().subscribe(
resp => {
this.fliterRole(resp);
},
err => {
this.loading = false;
this._nzMessage.create('error', `Error occurred: ${err.message}`);
}
);
filterRole(result) {
for(let i =0; i < result.length; i++) {
this.filterrole.push({ text: result[i], value: result[i] });
}
}
this is working example https://codesandbox.io/s/525xw2097n
Upvotes: 3
Reputation: 538
Just do it like this
resp => {
this.filterrole = resp.map(x => ( {text: x, value: x } ))
},
and change the Role class to an interface
export interface Role {
text: string;
value: string;
}
Or if you still want to have it as a class then create a constructor
export class Role {
constructor(public value: string, public text: string)
}
and then
resp => {
this.filterrole = resp.map(x => new Role(x,x));
},
or if you want just mutate the array without reassigning:
resp => {
resp.forEach(x => this.filterrole.push(new Role(x,x)) );
},
but in this case don't forget to initalize filterrole somewhere.
Upvotes: 1
Reputation: 186
You can push the api response with below code. let me know if you had any trouble assigning to it.
`resp => {
// what should i do here to push the data into
// filterdata.text and filterdata.value
for (i in resp.data) {
filterrole.push(resp[i]);
}
}`
Upvotes: 0