2017-10-26 6 views
3

私はangleの新しいhttpクライアントモジュールの使い方を学んでいます。私は残りのAPIを消費しようとするとundefinedのプロパティ 'data'を読み込むことができません。 はここ Angularの新しいhttpクライアントエラー未定義のプロパティ 'data'を読み取れません

<div style="text-align:center"> 
    <h1> 
    Welcome to {{title}}! 
    </h1> 
    <button (click)="getPosts()">Get Posts</button> 
    <div *ngFor="let result of results.data"> 

     {{ result | json }} 

    </div> 
</div> 

はここ

import { Component, OnInit } from '@angular/core'; 
import {HttpClient} from '@angular/common/http'; 

interface ItemsResponse { 
    data: any[]; 
} 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 

export class AppComponent implements OnInit { 
    results: any; 
    // Inject HttpClient into your component or service. 
    constructor(private http: HttpClient) {} 
    title = 'School2College'; 

    ngOnInit(): void { 
    } 
    getPosts() { 
    this.http.get<ItemsResponse>('https://reqres.in/api/users?page=3').subscribe(res => 
     this.results = res); 
    } 
} 

は何故でしょう私のapp.component.tsだ、私のapp.htmlだ未定義のプロパティ 'データ' を読み取ることができません、エラー?

答えて

3

あなたは非同期要求を作っているので、最初に結果は結果が存在するかどうかを確認してからデータを

<div *ngFor="let result of results?.data"> 
     {{ result | json }} 
</div> 
+0

安全ナビゲーションオペレータとは何ですか?もう少し説明できますか? – Karty

+0

セーフナビゲーション演算子を使用すると、存在しないオブジェクトのオブジェクトプロパティにアクセスしようとすると、Angularがエラーをスローするのを防ぐことができます。 – Sajeetharan

+0

何をするより良い方法?代わりにngIFを使用することもできますが、これはより良いオプションになります – Sajeetharan

0

にアクセスするためにsafe navigation operatorを使用し、未定義になりますプロパティを読み取ることができません未定義の「データ」は単に結果が定義されていないことを意味します。 console.logを入力するか、ブレークポイントを適用し、定義されていない理由を調べてみてください。ブレークポイントを適用すると、定義されていない正確な理由がわかります。理由を知ることは重要です。 @Sajeetharanで説明したように

2

問題は同じです。

あなたは非同期要求を作っているので、最初は結果が 不定になり、

あなたは2つの方法でそれを解決することができます:

1)最初の初期値を入力してください。

export class AppComponent implements OnInit { 
    results:Array<any> = []; // code changed 
    ... 
    getPosts() { 
     this.http.get<ItemsResponse>('https://reqres.in/api/users?page=3').subscribe(res => 
     this.results = res.data); // code changed 
    } 
} 


<div *ngFor="let result of results"> 
    {{ result | json }} 
</div> 

2)は、安全なナビゲーション演算子

<div *ngFor="let result of results?.data"> 
    {{ result | json }} 
</div> 

を使用しますが、それは第二の方法を使用する標準的な方法です。

+0

ありがとうございました。私はサービスからgetposts()メソッドにアクセスし、app.component.tsからその関数にサブスクライブしたいと思いますか? – Karty

+0

ありがとうございました。あなたが私の質問に投票できるなら、いいですね。 – Karty

+0

サービス: getPosts(){ 返すthis.http.get ( 'https://reqres.in/api/users?page=3').map(res => res.json()) ; }コンポーネント:。 this.postService.getPosts()サブスクライブ(RES => this.results = res.data)。 –

関連する問題