如何在angular2或Ionic中应用* ngFor

时间:2017-06-22 06:43:25

标签: javascript angular typescript ionic2 ionic3

我正在研究Ionic Project。在按钮单击时,请求处理并收到数据,如下所示:

   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}}没有返回名字。

请指出我犯错的地方。

2 个答案:

答案 0 :(得分:3)

您使用test33作为变量但不是属性,这意味着ngFor无法在组件的属性上查看test33。

所以你需要做的是将test33声明为属性this.test33;,然后ngFor将知道该属性。

请记住 如果要在模板上使用代码中的变量,则必须将它们声明为组件属性。

希望这对你有所帮助。

编辑:

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

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

  test33;
  andAnyPropYouWantHere;

  constructor() {}

}

然后你声明的所有道具都可以在模板上使用ngFor,ngIf等等:)

答案 1 :(得分:2)

问题是test33是局部变量,而不是组件的属性,因此视图无法访问其值。

要解决此问题,请将test33声明为组件

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

    public test33: any;

    //...

}

然后使用login()

this.test33方法中设置其值
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);
      });
  }

现在应该按照预期在视图中显示。