簡體   English   中英

如何在angular2或Ionic中應用* ngFor

[英]How to apply *ngFor in angular2 or in Ionic

我正在從事離子項目。 在單擊按鈕時,正在處理一個請求,並接收到數據,如下所示:

   public login() {
    //this.showLoading()
    var test33;
    this.auth.login(this.registerCredentials).subscribe(data => {
      console.log(data["_body"])
      test33 = data["_body"]
      console.log(test33)
    },
      error => {
        this.showError(error);
      });
  }

鑒於:

 <ion-row class="logo-row">
        <ion-col></ion-col>
        <h2  *ngFor="let user0 of test33">{{ user0.name }}</h2>
        <ion-col width-67>
          <img src="http://placehold.it/300x200"/>
        </ion-col>
        <ion-col></ion-col>
      </ion-row>`

在控制台上,我在test33變量中接收數據為:

 [{"id":1,"role_id":1,"name":"Dr. Admin","email":"admin@admin.com","avatar":"\/user\/1\/profile\/HR1-dummy-avater.png","password":"$2y$10$iEpnh6pJ09rxH5NFFCVzaewBCxC\/FHZuHnkWA6qUrOBO3tYIBbsVC","remember_token":"VgwXUdIpL6EqW7Fp66VGRPjSKE727Inc4MTseJQq84cTCglkS335KCqVnavu","created_at":"2017-05-25 22:46:10","updated_at":"2017-06-14 05:19:52","is_feature":null}]

但是{{user0.name}}沒有返回名稱。

請指出我在哪里犯錯。

您將test33用作變量而不是屬性,這意味着ngFor無法在組件的屬性上查看test33。

因此,您要做的就是將test33聲明為屬性this.test33; 然后ngFor會知道該屬性。

請記住,如果要在模板上的代碼中使用var,則必須將它們聲明為組件屬性。

希望這對您有所幫助。

編輯:

import { Component } from '@angular/core';

@Component({
  selector: 'home-page',
  templateUrl: 'home.html'
})
export class HomePage {

  test33;
  andAnyPropYouWantHere;

  constructor() {}

}

然后,您在那里聲明的所有道具都可以與ngFor,ngIf以及其他許多模板一起在模​​板上使用:)

問題在於, test33是局部變量,而不是component的屬性 ,因此視圖無法訪問其值。

要修復此問題, test33聲明為組件的屬性

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {

    public test33: any;

    //...

}

然后使用this.test33login()方法中設置其值:

public login() {
    //this.showLoading()
    // var test33; <- remove this line
    this.auth.login(this.registerCredentials).subscribe(data => {
      console.log(data["_body"])
      this.test33 = data["_body"]
      console.log(this.test33)
    },
      error => {
        this.showError(error);
      });
  }

現在,它應該按預期顯示在視圖中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM