我有服务
export class FoodService {
private foodUrl: string = "/url/to/data";
foodList: Food[];
constructor(private http: Http) { }
getFoodList(): Observable<Food[]>
{
return this.http.get(this.foodUrl)
.map(response => response.json() as Food[]);
}
}
返回Observable<Food[]>
。
在一个组件中,我订阅了返回的Observable
。我在ngOnInit()
- 函数:
export class ResultComponent implements OnInit {
foodList: Food[];
constructor(private foodService: FoodService) { }
ngOnInit() {
this.tags = this.optionService.tags;
this.foodService.getFoodList()
.subscribe(list => this.foodList = list);
}
}
这一切都很好。但现在我想处理foodList
并且我一直在收到错误,因为在处理时它仍然是未定义的。我甚至尝试在onCompleted
调用中将我的处理函数作为subscribe
参数传递。
有没有办法等到数据被提取?
//编辑:
在我的处理步骤中,我循环数组并计算一些东西。错误来自forEach
:
evaluateTags(): void
{
this.foodList.forEach(
//list.forEach(
food =>
{
var count: number = 0;
this.tags.forEach(
tag =>
{
if (food.tags.includes(tag))
{
count++;
}
}
);
food.hitrate = count / food.tags.length;
}
);
}
答案 0 :(得分:2)
只需在订阅中进行处理吗?
this.foodService.getFoodList()
.subscribe(list => {
this.foodList = list;
this.evaluateTags();
});