2017-02-13 42 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