无法在Angular 5中将一个数组的内容复制到另一个数组

时间:2018-05-25 11:19:18

标签: javascript angular angular5

我的组件中有一个这样定义的空数组:

private dtoList=[];

我使用HttpClient调用服务从后端获取数据并返回包含列表的对象:

    this.appService.getData()
        .subscribe((response) => {
          let value = response;
            //1st way
          this.dtoList = response['dtoList'];
          console.log(this.dtoList)
          //2nd way
          this.dtoList = cloneDeep(response['dtoList']);
          console.log(this.dtoList)
   });

值字段中收到的回复是:

Object {success: false, description: null, dtoList: Array(2), status: null}

响应对象中收到的列表未被复制到目标列表中。 目标列表始终显示为未定义。

任何帮助都将不胜感激。

5 个答案:

答案 0 :(得分:0)

试试这个

response['dtoList'].forEach(element=>{ this.dtoList.push(element); });

答案 1 :(得分:0)

使用JSON.parse(JSON.stringify(obj))尝试克隆数组中的对象

this.appService.getData()
        .subscribe((response) => {
          response['dtoList'].forEach((obj, index) => this.dtoList[index] = JSON.parse(JSON.stringify(obj)));
          console.log(this.dtoList)
});

答案 2 :(得分:0)

your declaration is wrong for private dtoList=[]; 

declare like  dtoList:any=[]; than assign object like below
 constructor(){
    this.dtoList={success: false, description: null, dtoList: ['dat1','data2'], status: null}
    console.log(this.dtoList);
    console.log(this.dtoList.dtoList);
  }

答案 3 :(得分:0)

请这样试试。为结果列表项创建class(model),为Observable方法设置通用getData类型。

<强> service.ts

@Injectable()
export class AppService {

  constructor(private http: HttpClient) { }

  getData(): Observable<ResultModel> {
    return this.http.get<ResultModel>('url for api');
  }

}

export class ResultModel {
  id: number;
  title: string;
}

<强> component.ts

private dtoList: ResultModel[] = [];
 this.appService.getData()
    .subscribe((response) => {
        this.dtoList = response;
        // if here you want copy array, you can use spread operator
        // this.dtoList = [...response];
     });

答案 4 :(得分:0)

发生的现象并不十分清楚,但如果我以单独的方法复制返回的响应的内容,它似乎有效。因此,我没有在匿名订阅函数中复制响应内容,而是将其传递给另一个要复制的方法。它以这种方式工作。

public class FlyE implements Listener {

  @EventHandler
  public void onPlayerMovement(PlayerMoveEvent e) {
      Player p = e.getPlayer();
      double y1 = p.getLocation().getY();
      // wait 1 second
      double y2 = p.getLocation().getY();
      double yf = y1 - y2;
      Bukkit.broadcastMessage(p + " Increase = " + yf);   

  }
}