2017-06-07 3 views
1

私はthis guideを使って角2のHTTP要求を学習しています。私のオブジェクトの配列は、http.get()の要求の後でも未定義です。角2 - オブジェクトの配列は、依然としてHTTPリクエストの後に未定義です

サービスコード:

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:未定義のforEach 'プロパティを読み取ることができません"。

私はPostmanとApplication Insightsでテストしたため、リクエストはエラーではありません(私のAPIは.NET Core APIです)。応答コードは200です。 他の場所で問題が発生していますが、見つけられません。

ありがとうございました!

+1

サブスクライバ内のforeachを移動してみてください –

答えて

2

のようなものを試してみてください。 httpリクエストがajaxなので、それは起動され、その後のコードは起動されます。

サブスクリプションのコールバックに次のコードをドロップする必要があります。これにより、応答がサーバーから返されたことが確認された後にのみ起動されます。

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

ありがとうございました! – GSeriousB

1

は、私は問題はhttpリクエストが完了する前に解雇された以下のコードによって引き起こされると考えてい

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

ありがとうございました! – GSeriousB

関連する問題