データを取得する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
としてエラーが発生しますか?
HttpはAJAXリクエストを使用します。 Aは非同期を意味します。約束の全ポイントは、非同期操作の将来の結果を表すことです。 getSurveys()**リクエストを送信した後、すぐに戻ります。アンケートは、then()に渡されたコールバック関数が実行されたときにのみ使用できます。 then()に渡されたコールバックの中に 'this.keys = Object.keys(this.surveys);'行**を入れてください。 –
[非同期呼び出しから応答を返すにはどうすればよいですか?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –
[Anger Observable/http/async呼び出しからの応答を返すにはどうすればいいですか?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from- a-observable-http-async-call-in-angular2) – Alex