2017-06-03 3 views
0

データを取得するAPI呼び出し用のサービスを作成しました。以下は私のサービスコードです。以下はAngular2の "未定義またはnullをオブジェクトに変換できません"に対処する方法

export class SurveyServiceService { 

    private surveysUrl = 
    'http://107.170.59.79/services/public/api/v1/countries'; 
    private headers = new Headers({'Content-Type': 'application/json'}); 

    constructor(private http: Http) { } 

    getSurveys(): Promise<Survey[]> { 
    return this.http.get(this.surveysUrl) 
     .toPromise() 
     .then(response => response.json() as Survey[]) 
     .catch(this.handleError); 
    } 
} 

私は中* ngForを使用して、それを繰り返すことができるように、私は、コードの下に使用して配列に変換しようとしたJSONオブジェクト内のデータを取得していますのでgetSurveysのための私のコンポーネントは

export class SurveysComponent implements OnInit { 

    title = 'Survey List'; 
    surveys: Survey[]; 
    keys: String[]; 
    selectedSurvey: Survey; 

    constructor(private router: Router, 
    private surveyService: SurveyServiceService) { } 

    ngOnInit(): void { 
    this.getSurveys(); 
    this.keys = Object.keys(this.surveys); 
    } 

    getSurveys(): void { 
    this.surveyService.getSurveys().then(surveys => this.surveys = surveys); 
    } 
} 

機能ですHTML。

this.keys = Object.keys(this.surveys); 

しかし、私は、コードを実行したとき、私は、誰かが私が間違っていた場所を私に教えてくださいすることができ

TypeError: Cannot convert undefined or null to object 

としてエラーが発生しますか?

+0

HttpはAJAXリクエストを使用します。 Aは非同期を意味します。約束の全ポイントは、非同期操作の将来の結果を表すことです。 getSurveys()**リクエストを送信した後、すぐに戻ります。アンケートは、then()に渡されたコールバック関数が実行されたときにのみ使用できます。 then()に渡されたコールバックの中に 'this.keys = Object.keys(this.surveys);'行**を入れてください。 –

+1

[非同期呼び出しから応答を返すにはどうすればよいですか?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –

+0

[Anger Observable/http/async呼び出しからの応答を返すにはどうすればいいですか?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from- a-observable-http-async-call-in-angular2) – Alex

答えて

2

@JB Nizetのコメントは正しい解決策ですが、私は明確なコードのために答えをここに入れます。

0

パイプを使用しようとしましたが、同じ問題が発生しました。 代わりに、これを回避策として使用します。

.subscribe(
    res => 
    { 
    this.apiarray = []; <--- Empty array here 
    console.log("response form api : " + JSON.stringify(res)); 
    this.ResultfromApi= res; 
    this.apiarray.push(this.PatientInfoFromApi); 
    } 

これで、オブジェクトではなく配列を反復処理するだけです。テンプレートでは あなたの* ngForループはこのようになります

<tr *ngFor="let item of apiarray"> 
    <td>{{item.specific_key_to_your_result}}</td> 
    ... 
</tr> 
関連する問題