我下面的代码段不起作用。最后,对该服务的调用进行了一个http调用,该调用显示在网络日志中,表明已返回数据,但没有以valuChanges代码段的形式将确切的数据用于循环。更令人惊讶的是,在我的组件的构造函数中对服务进行了相同的调用,并且效果很好。
const values = this.testService.getPosts();
this.form.valueChanges.subscribe((val) => {
const temps: testModel[];
temps = this.testService.getPosts();
cn = val['name'];
format = val['cs'];
// The console.log below mysteriously outputs data, and shows
// There is data in the array variable
console.log(temps);
if (format == 'a') {
this.testModel = temp;
} else {
for (let i = 0; i < temps.length; i++) {
// The log below prints out no data
// Also when I go ahead and debug the array is empty. Even
// the network output shows returned data
console.log(temps[i]);
}
}
});
这是testService中的getPosts方法的样子
getPosts() {
const tempModel: testModel[] = [];
this.dataSource.getPosts().subscribe(response => {
if (response) {
let value = response;
value.forEach(tp => {
const temp = new testModel();
Object.assign(temp, tp);
tempModel.push(temp);
});
}
});
return tempModel;
}
答案 0 :(得分:1)
return语句应该在订阅中,或者您应该使用map
而不是subscribe
。与此类似:
getPosts() {
const tempModel: testModel[] = [];
return this.dataSource.getPosts()
.map(response => {
if (response) {
let value = response;
value.forEach(tp => {
const temp = new testModel();
Object.assign(temp, tp);
tempModel.push(temp);
});
return tempModel;
}
return tempModel;
});
}
执行此操作后,您将必须订阅从此处返回的内容,以便获得未包装的值。与此类似:
this.form.valueChanges.subscribe(val => {
this.testService.getPosts().subscribe(tempModel => {
const temps: testModel[];
cn = val['name'];
format = val['cs'];
format === 'a' ? this.testModel = temp : temps.forEach(temp => console.log(temp));
});
});
答案 1 :(得分:1)
您的getPosts
方法在返回之前不会等待服务调用完成,因此会得到一个空数组。就目前而言,您的代码显示为declare an empty array
-> start http request
-> return current array
。
您的服务方法不应(也不能)返回数组。相反,它应该返回Promise
或Observable
供调用者处理。
getPosts() {
return this.dataSource.getPosts().map(response => {
const tempModel: testModel[] = [];
if (response) {
let value = response;
value.forEach(tp => {
const temp = new testModel();
Object.assign(temp, tp);
tempModel.push(temp);
});
}
return tempModel;
});
}
然后,您需要以等待返回的方式调用该调用
this.form.valueChanges.subscribe((val) => {
const temps: testModel[];
cn = val['name'];
format = val['cs'];
this.testService.getPosts().subscribe(temps => {
console.log(temps);
if (format == 'a') {
this.testModel = temp;
} else {
for (let i = 0; i < temps.length; i++) {
console.log(temps[i]);
}
}
}
});