2016-07-02 4 views
0

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(画像)表示未定義

私は私が間違って何をしたかについての非常に困惑していますどんな援助も本当に感謝しています。

答えて

7

JSON構造体は配列です。あなたはその配列のdata属性にアクセスしようとしています。しかし配列にはdataという属性はありません。

response.json()があなたの配列です。追加する必要はありません.data

+0

ニースキャッチ@JBNizet!雷の速い返信ありがとうございました。私は完全にこの1つを逃した、今それは正常に動作している! –

2

チェック

getImages(imagesUrl) : Promise<Image[]> { 
    return this.http.get(imagesUrl) 
      .toPromise() 
      .then(response => response.json().data) 
}; 

response.json()で何かを持っている場合。

.then(response => { 
    console.log(response.json()); 
    return response.json().data) 
}) 
+0

Andreiにもお返事ありがとうございます!私はデバッグを心がけています。 @JBNizetの答えで私の問題を解決しました。 –

3

欠落しているデータ属性の問題は、静的モックからInMemoryDataServiceを使用するようにデータを変更するときに説明されている手順の中で、第6部の "Tour of Heroes" Angular2チュー​​トリアルの根本的な問題です。

getHeros()メソッドとgetHeros(id)メソッドの両方にこの問題があります。式の '.data'部分を削除すると、 'undefined'の結果が解決されます。

関連する問題