2017-09-27 64 views
0

我是angular2中的新成員,我想循環鍵並將user_id更改爲用戶名。這是user.component.ts的代碼。作爲迴應,我越來越像這樣:[{「1」:「Begginer,professional,」},{「2」:「Begginer」},{「4」:「專業,新鮮」}]我想展示它像:循環插入角度2中的散列鍵中的值

甲初學者,專業

乙Begineer

C專業,更新鮮

ABC是用戶名。

this.userCategories = response; 
console.log(JSON.stringify(this.userCategories)); //[{"1":"Begginer ,professional ,"},{"2":"Begginer"},{"4":"Professional, freshers"}] 
this.userCategories = this.userCategories.map(i => { 
    let user = []; 
    let usr = []; 
    const User_id = Object.keys(i)[0]; // here I am getting user_id 
    for(let j of User_id){ 
    this.userService.userName(j).subscribe(
    name => { 
     usr.push(name); // pushing name of users in an array. 
     return usr; 
    }, 
    err => { 
     console.log('err:', err); 
    } 
    ); 
    } 
    user[0] = usr; 
    console.log(user[0]); // here I am getting username in an array. 
    user[1] = i[User_id]; 
    return user; 
}) 

然後在視圖時,我使用的是這樣的:

<a >{{userCategories[0] | json}}</b> 
<a >{{userCategories[1]}}</a> 

我越來越:

[ "\"A \"" ] Begineers,professional 
    [ "\"B \"" ] Begineers 
    [ "\"C \"" ] Professional,fresher 

任何人都可以請幫助我。提前致謝。

回答

0

嘗試類似: -

let response = [{ "1": "Begineer ,professional ," }, { "2": "Begineer" }, { "4": "Professional, freshers" }]; //JSON Array [{"1":"Begineer ,professional ,"},{"2":"Begineer"},{"4":"Professional, freshers"}] 
/** 
* Please make sure map always return array 
* map() method creates a new array with the results of calling a function for every array element. 
* 
* And your parsing as Object {"A" : "Begineer,professional"} 
* 
* to make it as Object use it as 
*/ 
response.map((value, key) => { 
    //Get UserName By UserID Function 
    let userId = Object.keys(value)[0]; 
    this._service.username(userId).subscribe(name => { 
     this.userCategories.push({key : name , username : value[userId]}) ; 
    }) 
}) 

由於* ngFor可與陣列我已經轉換它作爲數組..

請更新您的視圖: -

<div *ngFor="let user of userCategories"> 
     <p> 
       <a>{{user.key}}</a> 
       <a>{{user.username}}</a> 
     </p> 
</div> 
+0

我已經編輯我的問題像你已經發布,但我沒有得到輸出。 –

+0

* ng只適用於數組而非對象,,請參閱更新後的答案 –

+0

感謝@Double H,現在我正在瀏覽器控制檯中獲取此內容。 錯誤類型錯誤:{{用戶.KEY}}無法讀取未定義 –