1

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!

1
  • 1
    Try moving the foreach inside the subscribe Commented Jun 7, 2017 at 12:37

2 Answers 2

2

I believe the issue is caused by the below code being fired before the http request is finished. Since the http request is ajax it get fired and then the code after that is fired.

You need to drop the below code into the callback of the subscription so that it only fires once you are sure response has been returned from the server.

this.companyService.getUserCompaniesByUserId(localStorage.getItem('user_id')).subscribe(
    uc => {
      this.userCompanies = uc;
      this.userCompanies.forEach(uc => { ... }); 
   },
   error => this.errorMsg = <any>error
  );
Sign up to request clarification or add additional context in comments.

Comments

1

Try something like

this.companyService.getUserCompaniesByUserId(localStorage.getItem('user_id'))
                        .subscribe(uc => {
                         this.userCompanies = uc
                         this.userCompanies.forEach(uc => {});     
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.