我在我的应用程序construct()
中调用外部json,在控制台日志中我看到了正确的结果:
var url = 'https://my_path.co/apiv1/products';
this.http.get(url).map(res => res.json()).subscribe(items => console.log(items));
我试过了:
this.http.get(url).map(res => res.json()).subscribe(items => items);
and
this.http.get(url).map(res => res.json()).subscribe(items => {items => items});
使用*ngFor
我没有得到任何结果,如果我在构造一个字符串中创建我无法在{{my_string}}
如何将json结果传递给view以列出所有元素?
答案 0 :(得分:0)
为了在视图中显示结果,您需要在组件中声明一个属性,并将要在视图中显示的内容分配给该属性:
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public items: any; // This creates a public property (accessible from the view), called items, whose type is any (could assign anything to it).
public myString: string;
// It's better to avoid making http calls in the constructor, we should use ionViewWillLoad / ionViewWillEnter or any other life cycle hood
constructor() {}
ionViewWillLoad() {
let url = 'https://my_path.co/apiv1/products';
this.myString = 'Demo app!';
this.http.get(url)
.map(res => res.json())
.subscribe(itemsFromServer => {
// Here you can assign the result (itemsFromServer) to the property from the component (would be this.items)
this.items = itemsFromServer;
console.log(this.items)
});
}
}
现在,您可以在视图中使用items
和myString
属性,如下所示:
<ion-header>
<ion-navbar color="primary">
<ion-title>{{ myString }}</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item *ngFor="let item of items">
{{ item | json }}
</ion-item>
</ion-content>