Angular2 RC3(TypeScript)を学ぶための非常に簡単なWebプロジェクトをセットアップしました。私は現時点でバックエンドを持っておらず、HTTP GETリクエストを使ってJSONファイルからいくつかの画像をロードしようとしています。Angular2 RC3 httpサービスから返されたデータは定義されていません
サービスの作成に関する公式文書に従っており、すべてが例外やエラーなしで実行されます。しかし、HTTP GETリクエストが正常に完了しても、私のサービスから返されるデータは常に未定義であり、Firebugで応答データを見ることができます。以下の私がこれまでに行ったことある...
images.jsonファイル:
[
{
"description": "image1",
"file": "image1.jpeg"
},
{
"description": "image2",
"file": "image2.jpeg"
},
{
"description": "image3",
"file": "image3.jpeg"
}
]
JSONファイルをロードするための責任サービスの一部を次のようになります。
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
....
constructor(private http: Http) {}
getImages(imagesUrl) : Promise<Image[]> {
return this.http.get(imagesUrl)
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);
};
画像はシンプルなクラスです:
export class Image {
description : string;
file : string;
}
サービスを利用する
コンポーネントは次のように一部になります、上から
...
@Component({
...
providers : [ ImageService ]
...
})
constructor(private imageService : ImageService) {}
ngOnInit() {
this.imageService.getImages(this.imageSrcDir + "images.json")
.then(images => console.log(images))
.catch(error => console.log(error));
}
にconsole.log(画像)表示未定義
私は私が間違って何をしたかについての非常に困惑していますどんな援助も本当に感謝しています。
ニースキャッチ@JBNizet!雷の速い返信ありがとうございました。私は完全にこの1つを逃した、今それは正常に動作している! –