2017-06-22 53 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