简体   繁体   中英

How to copy values from one array of objects to another array of objects in typescript, angular 4?

I have an Angular component that needs an array of objects! I wrote the code for fetching the array in a service:

    private roles_list = [];

    getRoles(): any[]  {
        return this.roles_list;
             }

    roles(){

    const promise = new Promise( (resolve, reject) => {
            return this._http.get('/api/getData')
                .subscribe(data => {
                    //this.roles_list = data
                    for (var i=0 ; i < Object.keys(data).length ; i++){
                        var temp = {};
                        temp["role"] = "role";
                        temp["value"] = data[i].key;
                        this.roles_list.push(temp);
                    }

                    console.log("data");
                    console.log(data);
                    console.log("roles_list");
                    console.log(this.roles_list);
                    resolve(this.roles_list);
                },
                err => {
                    reject(err);
                });
        });
    return promise;
}

I'm then resolving the promise in a component:

private roles = [];
this.getDataService.roles().then(res => {
      console.log(typeof(res));

       this.roles =  res.map(o => {
          return {name: o.name,role: o.role}
      });
  });

However this is throwing various errors, it says "the map method is not available for {}" although res should be an array not an object? any help is appreciated.

Edit: I solved the problem by sending a JSON object through resolve() and then doing the processing on the component's ngInit(), does anybody know why this problem occured? can we only send object's through resolve ?

Try this

private roles = [];
this.getDataService.roles().then(res => {
    console.log(typeof(res));

    for(let r of res){
        this.roles.push({name: r.name,role: r.role})
    }

});

I figured out what the problem was, apparently a promise can only pass a single object through it's resolve method. Hence when I pass an array of objects through it, it considers it just an object, and obviously, an object can not be assigned to an array of objects. The way to do it was to create an observable in the service and subscribe to it in the component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM