【问题标题】:Angular 2 - Array of Objects is still undefined after a HTTP RequestAngular 2 - 对象数组在 HTTP 请求后仍未定义
【发布时间】:2017-06-07 12:33:16
【问题描述】:

我正在使用this guide 来学习 Angular 2 http 请求。在http.get() 请求之后,我的对象数组仍未定义。

服务代码:

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);
}

组件代码:

getCompanies() {
    this.companyService.getUserCompaniesByUserId(localStorage.getItem('user_id'))
                            .subscribe(
                                uc => this.userCompanies = uc,
                                error => this.errorMsg = <any>error
                        );

    this.userCompanies.forEach(uc => {
        ...
        ...
    });
}

因为请求后userCompanies数组是未定义的,所以不会进入forEach()循环。它会抛出这个错误:“TypeError: Cannot read property 'forEach' of undefined”。

不是请求是错误,因为我使用 Postman 和 Application Insights 对其进行了测试(我的 API 是 .NET Core API)。响应代码为 200。 问题出在其他地方,但我找不到。

谢谢!

【问题讨论】:

  • 尝试在订阅中移动foreach

标签: arrays angular object request undefined


【解决方案1】:

我认为这个问题是由于在 http 请求完成之前触发了以下代码。由于 http 请求是 ajax,因此它会被触发,然后触发之后的代码。

您需要将以下代码放入订阅的回调中,以便只有在您确定服务器已返回响应时才会触发它。

this.companyService.getUserCompaniesByUserId(localStorage.getItem('user_id')).subscribe(
    uc => {
      this.userCompanies = uc;
      this.userCompanies.forEach(uc => { ... }); 
   },
   error => this.errorMsg = <any>error
  );

【讨论】:

    【解决方案2】:

    试试类似的东西

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

    【讨论】:

      猜你喜欢
      • 2019-06-17
      • 1970-01-01
      • 2015-07-08
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      相关资源
      最近更新 更多