I have a service
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[]);
}
}
which returns an Observable<Food[]>
.
In a component I subscribe to the returned Observable
. I do this in the ngOnInit()
-function:
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);
}
}
This all works just fine. But now I want to process the foodList
and I keep getting errors because at the time of the processing it is still undefined. I even tried passing my processing function as onCompleted
parameter in the subscribe
call.
Is there a way to wait till the data is fetched?
//edit:
In my processing step I loop the Array and count some things. The Error origins from 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;
}
);
}