繁体   English   中英

离子框架,通过var从构造视图?

[英]Ionic framework, pass var to view from construct?

我在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结果以查看列出所有元素?

为了在视图中显示结果,您需要在组件中声明一个属性,并将想要在视图中显示的内容分配给该属性:

@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)

      });
    }

}

现在,您可以在视图中使用itemsmyString属性,如下所示:

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM