2017-09-27 75 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}}无法读取未定义 –