2017-06-22 54 views
0

我正在研究离子项目。这里按钮点击,请求是过程和数据被接收为示出以下内容:如何在angular2或Ionic中应用* ngFor

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

在控制台I接收到该数据中test33变量为:

[{"id":1,"role_id":1,"name":"Dr. Admin","email":"[email protected]","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}}不返回名称。

请指出我犯错的地方。

回答

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,和这么多的人:)

+0

如何将其声明为属性。因为现在当我注释掉'var test33'并将'test33'更改为this.test33'时,在'LoginPage'类型中不存在'Property'test33'的错误。' – Mohammed

+0

编辑后的回答为 –

2

问题是test33是一个局部变量,而不是来自组件的属性,所以视图无法访问其值。

为了修正它,申报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); 
     }); 
    } 

现在它应在显示按预期查看。

+1

两个答复是这种 – Mohammed

+0

correct.Thanks模板用呀,我们都在同一时间添加了答案,对不起!很高兴帮助:) – sebaferreras