Angular - Push API response into an array

angular observable array push
loop through observable array angular
angular 7 http get example
angular observable filter array of objects
angular 8 http get example
angular array of observables
rxjs observable array push
how to convert observable<any> to array

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

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

Angular subscribe push object to array, Had forked you Stackblitz Demo. If you want to manipulate your data after the HTTP Client response, you can actually do so by playing with the  Create the new array in a separate variable, and then write it into this.array in a single step. Only the javascript is currently displayed in your question, so I am taking a guess at what the template contains.


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.

Angular - Push API response into an array - angular - html, 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:  The user adds the data in the User interface, the controller gets the data in Array of the object as a model which we need to supply it REST API. So we need to convert this Array of objects to JSON objects. Read Data from Database. Angular application Consumes REST API data. This data is in the format of JSON format.


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]);
    }
}`

Observables Array Operations, flatMap((response) => response.json()) this.doctors.push(data); Now every object in our array has "Dr." prepended to the value of its name property. array operations you can employ in your Observables ; look for them in the RxJS API. Convert Object to Array Example. This section will see how we can convert Object to Array in Angular and Typescript with examples. Typescript Code. Let us assume that you have an object declared multiple properties. First Get the named keys using object.keys() method. This method retrieves keys from the given object and returns an array of keys.


Get data from a server, Next, still in the AppModule , add HttpClient to the imports array: Important: the In-memory Web API module has nothing to do with HTTP in Angular. In response to a click event, call the component's click handler, add() , and then clear the addHero({ name } as Hero) .subscribe(hero => { this.heroes.push(​hero); }); }. In this Angular 8 tutorial, we will show you a comprehensive step by step Angular 8 tutorial on consuming REST API using Angular HttpClient. As you see in almost Angular or MEAN stack tutorial in this site always uses REST API access.


KeyValuePipe, Transforms Object or Map into an array of key value pairs. See more {{ input_expression | keyvalue [ : compareFn ] }}. {{  Angular is a platform for building mobile and desktop web applications. Join the community of millions of developers who build compelling user interfaces with Angular.


AngularJS: API: $http, The following code demonstrates adding a new response transformation to be run We can't guarantee that the default transformation is an array defaults = angular. $httpProvider.interceptors.push(function($q, dependency1, dependency2)  You can make use of Array.push method to push a JSON object to an array list. let list = []; let myJson = { "name" : "sam" } list.push(myJson); console.log(list) Let’s look at another use case where you have to create a JSON object dynamically from an array and push to another array.