2017-05-25 124 views
0

我試圖從這個站點獲取JSON格式的數據https://api.chucknorris.io/(隨機笑話),但我得到一個錯誤:錯誤錯誤:無法找到不同的支持對象'[object Object] '類型'對象'。 NgFor僅支持與陣列等Iterables綁定。而 「DebugContext_ {視圖:對象,nodeIndex:11,nodeDef:對象,elDef:對象,elView:對象}」Angular 2 http - 從API獲取數據

這是routing.ts

import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 
import 'rxjs/add/operator/map'; 

@Injectable() 
export class RandomService { 
    constructor(private http: Http) { 
     console.log('working'); 

    } 
    getRandomJokes() { 
     return this.http.get('https://api.chucknorris.io/jokes/random') 
      .map(res => res.json()); 
    } 
} 

這是我想要的組件數據放入

<div *ngFor="let joke of jokes"> 
<h3>{{joke.value}}</h3> 
</div> 

`, 
providers: [RandomService] 

}) 
export class PocetnaComponent { 
jokes: Joke[]; 

constructor(private jokesService: RandomService){ 
this.jokesService.getRandomJokes().subscribe(jokes => {this.jokes = jokes}); 
} 

} 
interface Joke{ 
id: number; 
value: string; 
} 
+1

'getRandomJokes()'沒有返回數組等你笑話.. – echonax

回答

0

你是沒有約束力的陣列到*ngFor,你必須確保jokes實際上是一個數組,而不是一個亂開玩笑的對象。

要解決它,如果它是一個對象,你可以做this.jokes = [jokes]

+1

甚至不是在開玩笑 –

+1

這是一個很好的解決方案,但爲什麼還要設置陣列'jokes'?爲什麼不移除* ngFor並只顯示對象的屬性? – Alex

+0

@ AJT_82這就是我會做的,但這不是問題。因此它不是答案:) – Chrillewoodz

0

您提到的url只在對象中提供了單個值,因此您無法對其進行迭代。

也許,多次調用是這樣的:

getRandomJokes(n = 10){ 
    return Promise.all(Array(n).fill(0) 
      .map(() => this.http.get('https://api.chucknorris.io/jokes/random').toPromise() 
           .then(res => res.json())); 
} 

,並承諾使用

this.jokesService.getRandomJokes().then(jokes => {this.jokes = jokes}); 
0

您可以檢查它是否是一個數組,然後去ngFor或笑話轉換成陣列狀讓利笑話= [笑話];

<div *ngIf = "jokes.length > 0" ; else check> 
    <div *ngFor="let joke of jokes"> 
     <h3>{{joke.value}}</h3> 
    </div> 
</div> 
<ng-template #check> 
    <p>print the value of the object </p> 
</ng-template> 
0

可能是jokes不是數組。

<div *ngIf="Array.isArray(jokes)> 
<div *ngFor="let joke of jokes"> 
<h3>{{joke.value}}</h3> 
</div> 
1

由於您接收的不是數組,而是對象,因此您得到的錯誤是因爲對象無法被迭代。您可能想重新考慮命名,因爲我們只處理一個對象,joke將是一個更合適的名稱。但是,在這裏,我們使用jokes

所以,你應該做的是完全去除*ngFor,並只顯示與價值:

{{jokes?.value}} 

閒來無事需要:)注意這裏航行安全運營,保障其財產路徑null和undefined值。準備在異步世界中使用很多;)

以下是關於安全導航運算符的更多信息,從official docs