【发布时间】:2019-07-08 20:29:01
【问题描述】:
我有 angular 7 组件,它与模型相关联,并且该模型内部有一个数组,该数组是从服务中填充的。并且它已被填充。
问题是我无法映射数组,尽管它有元素。 当我控制台它显示数组有元素。然后我试图控制台 typeOf(array) 它总是给出对象,虽然它是一个数组!!。
我尝试使用this soluation,但也没有用。
请帮忙?
export class FooModel {
foo : Foo
bars: Bar[];
}
export class SomeComponent implements OnInit {
model: FooModel;
constructor(private service: ProjectService) {
this.model = new FooModel();
this.model.bars = [];
}
ngOnInit() {
this.service.getFoos().subscribe((result: any) => {
// data is populated fine
this.model= <FooModel>result.data;
});
Console.log(this.model); // the model has data at this point
const arr = this.model.bars.map(a=> {
// never comes here
return a;
});
console.log(arr); // nothing is displayed here
// this works why ??
const arr2 = [1,2,3].map(s=> {
return s;
}
console.log(arr2); // it displays [1,2,3]
}
}
【问题讨论】:
-
看起来
this.model仅在执行subscribe回调后才被填充,这将使这个问题成为How do I return the response from an asynchronous call? 的一个特例 -
其他人试图解释的...问题不在于
.map,而在于在哪里您拥有.map代码。它需要在传递给订阅方法的函数体内。否则,您将尝试在响应返回数据之前映射 。我有一个图表可以在这里完成这个过程:stackoverflow.com/questions/46769042/… -
@DeborahK 当我控制台记录它有数据的模型时,数据就在那里,我的问题是它认为数组是一个对象,尽管它是数组,所以它不能映射它
-
您能否构建一个简单的堆栈闪电战来演示您的问题?
标签: arrays angular typescript mapping