数组推送正在覆盖现有数组

问题描述 投票:0回答:3

我需要构建一个来自每个用户的数据响应数组。

import * as localforage from "localforage";

mobileData: any[] = [];

constructor(private dataService: DataService){}

ngOninit(){

    for(var i=0; i<users.length; i++){
        this.getData(users.id);
    }
}

getData(id) {

    this.dataService.getData(id).subscribe(response => {

        this.dataStorage(response);
    });
}

dataStorage(payload: any) {

    this.mobileData.push(payload);

    console.log("mobile data Array ", this.mobileData);

    if(this.mobileData.lenth === this.users.length){

       localforage.setItem("usersData", this.mobileData);
    }
}

问题是我的数组不断被新数据覆盖而不是附加。

//service
  getData(id:any): Observable<any> {
    let method                      = "GET";
    let url                             = "/api/getData";
    let data                            = "id="+id;
    let header:Headers                  = new Headers();
     header.set('Content-Type', 'application/x-www-form-urlencoded' );

     return this.http.request(this.newRequest(method,url,data,header))
       .map(this.extractData)
       .catch(this.handleError);
}

这是我第一次发帖。如果需要更多信息,请告知我们。

提前致谢。

javascript angular typescript
3个回答
0
投票

这应该可以解决问题。在订阅中简单地将response分配给mobileData,并在模板中使用mobileData来显示它。

mobileData = [];

this.dataService.getData(id).subscribe(response => {
    this.mobileData = response;
});

0
投票

ngOninit改为ngOnInit。我没有看到您的代码有任何其他错误。无论如何,我为你创造了this working example。将它与您的代码进行比较。


0
投票

export class HelloComponent implements OnInit {
	mobileData : any[] = [];
	isFinished = false;

	constructor(private dataService: DataService) {}

	ngOnInit(){
		for(var i=0; i<users.length; i++){
			this.getData(users.id);
		}
	}

	getData(id) {
		this.dataService.getData(id).subscribe(response => {
			this.dataStorage(response);
		});
	}
	
	dataStorage(payload: any) {
		this.mobileData.push(payload);
		console.log("mobile data Array ", this.mobileData);
		if(this.mobileData.length === this.users.length){
		   localforage.setItem("usersData", this.mobileData);
		}
	}
}
© www.soinside.com 2019 - 2024. All rights reserved.