2017-02-13 52 views
3

我從食譜的API中提取數據,我已經有一個可以正常工作的食譜列表,但是現在我要求單個食譜詳細信息(1個對象 )。我的控制檯日誌下面是JSON的樣子。無論我做什麼,我都無法在前端顯示,請儘可能地幫助。單個數組JSON對象不會打印(Ionic 2)

JSON

打字稿

details: any; 

loadDetails() { 
    if (this.details) { 
    return Promise.resolve(this.details); 
    } 

    return new Promise(resolve => { 
    this.http.get('http://api.yummly.com/v1/api/recipe/Crustless-Ham-Savory-Bake-2005439?_app_id=//////&_app_key=/////') 
     .map(res => res.json()) 
     .subscribe(data => { 
     console.log(data); 
     this.details = data; 
     resolve(this.details); 
     }); 
    }); 
} 

HTML

<ion-content> 
    <ion-list> 
     <ion-item> 
      <h1>{{details.id}}</h1> 
     </ion-item> 
    </ion-list> 
</ion-content> 

Pagename.ts

@Component({ 
    selector: 'page-details', 
    templateUrl: 'details.html', 
    providers: [ApiAuthentication] 

}) 
export class DetailsPage { 

    public api: any; 

    constructor(public navCtrl: NavController, public navParams: NavParams, public apiAuthentication: ApiAuthentication) { 
    this.loadRecipes(); 
    } 

    ionViewDidLoad() { 
    console.log('ionViewDidLoad DetailsPage'); 
    } 

    loadRecipes(){ 
    this.apiAuthentication.loadDetails() 
    .then(data => { 
     this.api = data; 
    }); 
    } 
} 
+1

我在返回的對象中沒有看到任何描述。你需要一個鍵來訪問try details.id forst來查看id是否正在打印 –

+0

@AniruddhaDas對不起,我現在已經改變爲ID(與其他值搞亂)我得到一個錯誤**無法讀取未定義的屬性'ID' * – BA1995

+0

@ BA1995。這是異步值的經典案例:在**'details'實際定義之前,您的模板嘗試訪問'details.id' **(因爲它是異步冷卻的結果,所以不會立即分配它)。嘗試在您的模板中使用{{details?.id}}。 – AngularChef

回答

2

您試圖顯示

<h1>{{details.id}}</h1> 

當你其實有api你的對象:

loadRecipes(){ 
    this.apiAuthentication.loadDetails() 
    .then(data => { 
     this.api = data; // you store it in api! 
    }); 

所以這應該可能是隻是改變你的模板位被清除出:

<h1>{{api.id}}</h1> 

也可能在這裏添加安全導航操作符。 {{api?.id}}

+0

太好了!我沒有意識到?'可以讓你通過錯誤 – BA1995

+1

安全的導航操作符保護空值,你可以在這裏閱讀更多:https://angular.io/docs/ts/latest/guide/template-syntax.html#!#safe-navigation-操作符因爲我們經常處理異步操作,所以您將習慣於使用Angular的這個LOT – Alex

0

你實際上是想許多事情,可以用一個完成砰砰聲。

您正在使用promise和observable,您可以避免其中之一。我會說使用可觀察,因爲它默認情況下。

loadDetails() { 
    if (this.details) { 
    return null; 
    } 

    this.http.get('http://api.yummly.com/v1/api/recipe/Crustless-Ham-Savory-Bake-2005439?_app_id=//////&_app_key=/////') 
     //.map(res => res.json()) // you don't need this 
     .subscribe(data => { 
     console.log(data); // make sure the data is the object you are expecting and have the id property 
     this.details = data; // not necessary if you will use async pipe 
     }); 
    }); 
} 

here details.id should be available。

+0

嗨,我已編輯我的問題,包括更多的代碼拉動該功能,我也需要'.map(res => res.json())'將json轉換爲對象 – BA1995