问题是尽管其中有元素,但我无法映射到数组。 当我控制台它显示数组具有元素。然后我试图安慰typeOf(array)它总是给对象,尽管它是一个数组!!。
我尝试使用this soluation,但也没有帮助。
有什么帮助吗?
<script type="text/javascript">
$(function(){
$("#linkContainer:nth-child(odd)").css('background-color', '#222');
});
$("#menuToggle").click(function(){
$("#sidebarContainer").animate({"left": "0px"});
});
</script>
答案 0 :(得分:2)
由于请求是异步的,因此您可能需要将逻辑放置在订阅中,
this.service.getFoos().subscribe((result: any) => {
// data is populated fine
this.model= <FooModel>result.data;
const arr = this.model.bars.map(a=> {
// never comes here
return a;
});
console.log(arr);
});
答案 1 :(得分:1)
订阅是异步的,因此在其仍在工作时,将执行执行堆栈中的下一行操作,在这种情况下,订阅后您拥有的映射将同时在后台填充。您可以尝试在另一个生命周期挂钩中进行映射,例如说viewChecked希望它能起作用。 #欢呼声
答案 2 :(得分:1)
请查看评论
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;
});
// the following starts to execute even before the model is populated above.
const arr = this.model.bars.map(a=> {
// never comes here because this.model.bars is empty at here and the length is 0 and nothing inside map executes
return a;
});
console.log(arr); // nothing is displayed here because it has nothing inside
// this works why ?? because you are using on an array which has some items.
const arr2 = [1,2,3].map(s=> {
return s;
}
console.log(arr2); // it displays [1,2,3]
}
}
因此,正如Sajeetharan所建议的那样,您将其保存在subscribe()