Language
:Ionic2。
Description
:我的想法是,我尝试使用提供商从云端获取数据。在home组件中,我调用提供者的方法并尝试将其结果分配给变量。但它不起作用。
Sample Code for provider's code
lastValues: any[][] = [[]];
constructor(public http: Http) {}
getLastValues() {
this.http.get("http://things.ubidots.com/api/v1.6/datasources/" + this.dataSourcaId + "/variables/?token=" + this.ubidotsToken)
.map(res => res.json().results).subscribe(data => {
this.lastValues = Array(Math.ceil(data.length / 2));
let rowNum = 0;
for (let i = 0; i < data.length; i+=2) {
this.lastValues[rowNum] = Array(2);
if (data[i]) {
this.lastValues[rowNum][0] = data[i].name;
// console.log(this.lastValues[rowNum][0]);
}
if (data[i+1]) {
this.lastValues[rowNum][1] = data[i+1].name;
}
rowNum++;
}
}, (err) => {
console.log(err);
});
return this.lastValues;
}
Sample code for home component
export class HomePage {
sensors: any[][];
constructor(public navCtrl: NavController, public dataService: Data, public platform: Platform) {
}
ionViewDidLoad(){
this.platform.ready().then(() => {
this.sensors = this.dataService.getLastValues();
});
}
test() {
console.log(this.sensors);
console.log(this.dataService.getLastValues());
}
}
在测试方法中,第一个命令打印空数组,第二个命令打印数据来自云。无法理解我做错了什么。
...谢谢
答案 0 :(得分:0)
之所以发生这种情况,是因为您正在发出http请求,但您的return this.lastValues;
不会等到该http请求完成。
第一次调用服务时,会发送http请求,并立即返回空的this.lastValues
。第二次调用服务时,你再次发出一个http请求(再次,没有完成),然后再次立即返回this.lastValues
矩阵,但这次它不是空的,因为第一个http请求在某个时刻结束,矩阵已初始化。
组织代码和避免异步问题的更好方法是:
<强>提供商强>
lastValues: any[][] = [[]];
constructor(public http: Http) {}
public getLastValues(): Observable<any> {
return this.http.get("http://things.ubidots.com/api/v1.6/datasources/" + this.dataSourcaId + "/variables/?token=" + this.ubidotsToken)
.map(res => res.json().results)
.map(data => {
this.lastValues = Array(Math.ceil(data.length / 2));
let rowNum = 0;
for (let i = 0; i < data.length; i+=2) {
this.lastValues[rowNum] = Array(2);
if (data[i]) {
this.lastValues[rowNum][0] = data[i].name;
// console.log(this.lastValues[rowNum][0]);
}
if (data[i+1]) {
this.lastValues[rowNum][1] = data[i+1].name;
}
rowNum++;
}
return this.lastValues;
});
}
所以基本上我使用map(() => {});
函数来转换数据,并返回this.http.get()
,最终会返回lastValues
矩阵。
通过这样做,您可以在组件代码中执行此操作,而不是订阅提供程序中的http.get()
,从而避免问题和错误,因为数据尚未准备就绪。
<强>组件强>
export class HomePage {
sensors: any[][];
constructor(public navCtrl: NavController, public dataService: Data, public platform: Platform) {
}
ionViewDidLoad(){
this.dataService.getLastValues().subscribe(result => {
this.sensors = result;
console.log(this.sensors);
}, error => {
console.log('An error has ocurred: ' + error);
});
}
test() {
this.dataService.getLastValues().subscribe(result => {
this.sensors = result;
console.log(this.sensors);
}, error => {
console.log('An error has ocurred: ' + error);
});
}