I'm using this guide to learn angular 2 http requests. My array of objects is still undefined after an http.get() request.
Service code:
getUserCompaniesByUserId(userId: string) : Observable<ApplicationUserCompany[]> {
return this.http.get(`${this.url}/${userId}`)
.map(res => res.json())
.catch(this.handleError);
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
Component code:
getCompanies() {
this.companyService.getUserCompaniesByUserId(localStorage.getItem('user_id'))
.subscribe(
uc => this.userCompanies = uc,
error => this.errorMsg = <any>error
);
this.userCompanies.forEach(uc => {
...
...
});
}
Because the userCompanies array is undefined after the request, it won't enter in the forEach() loop. It throws this error: "TypeError: Cannot read property 'forEach' of undefined".
Not the request is the error, because I tested it with Postman and Application Insights (my API is .NET Core API). The response code is 200. Somewhere else is the problem, but I cannot find it.
Thank you!