组件
export class AllUserComponent implements OnInit {
//Here is saving all users from database
allUsers: Array<Object>;
roleName: any[] = []; //here I want roles property from each object from allUsers
constructor(private userService: UserService) {}
ngOnInit() {
//Take from UserService getAll method and subscribe to add all users from database
this.userService.getAll().subscribe(data => {
this.allUsers = data.allUsers;
console.log(this.allUsers)
});
}
服务
getAll(): Observable<AllUsers> {
return this.http.get<AllUsers>(this.url);
}
模型
export interface AllUsers{
allUsers: string[];
}
我想获得在allUser
数组的每个对象中嵌套值的角色,并将其添加到roleName
数组中,并显示在HTML视图的Roles
的{{1}}列中
答案 0 :(得分:0)
尝试这样:
this.allUsers.forEch(user => {
user.roleNames.push(user.roles);
})
答案 1 :(得分:0)
让我们先更改字符串数组
export interface AllUsers{
allUsers: User[]; // shouldn't be a string array?!
}
添加用户
export interface User {
id: number;
firstName: string;
lastName: string;
email: string;
password: string;
roles: Role[];
}
和角色
export interface Role {
id: number;
name: string
}
尽量避免使用订阅,请改用异步管道。您可以使用lodash处理数组。
export class AllUserComponent implements OnInit {
allUsers$: Observable<User[]>;
distinctRoles$: Observable<Role[]>;
constructor(private userService: UserService) {}
ngOnInit() {
// Take from UserService getAll method
this.allUsers$ = this.userService.getAll().pipe(
map((all: AllUsers) => all.allUsers),
);
// map the roles
this.distinctRoles$ = this.allUsers$.pipe(
map((allUsers: User[]) => _.flatMap(allUsers, 'roles')), // import * as _ from 'lodash'
map((allRoles: Role[][]) => _.flatten(allRoles)),
map((allRoles: Role[]) => _.uniq(allRoles)), // remove the line if you don't want disctinct
);
}
然后使用异步管道在模板中“订阅”您的Observables
<div *ngFor="let role of disctictRoles$ | async">
答案 2 :(得分:-1)
我认为您正在使用matTable
或至少使用*ngFor
;因此,您需要添加一个函数来获得适当的角色;喜欢:
getRoles(user: Object) {
return user.roles.reduce((str, role) => {
// add role name if this is the first role; else add role to string then return it
return str? str += ', ' + role.name: role.name;
}, '');
}
没有必要使用reduce函数;您可以在普通循环中使用临时变量;但这是更干净的方法。
然后可以从HTML中以角色td
进行调用;喜欢:
<tr *ngFor="let user of allUsers">
<!-- previous details-->
<td> {{getRoles(user)}} </td>
</tr>
详细了解reduce函数。