将值从数组添加到其他数组 [英] Add value from Array to other array

查看:54
本文介绍了将值从数组添加到其他数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

组件

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 数组中并显示在 Roles 列中在HTML视图的 table 中.

I want to get roles which are nested values in each object of allUser array and add it to roleName array and display in Roles column in table in HTML view.

推荐答案

让我们先更改字符串数组

Lets's change that string array first

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处理数组.

Try to avoid using subscribe, use async pipe instead. You could use lodash to handle your arrays.

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

And "subscribe" to your Observables in your template with async pipe

<div *ngFor="let role of disctictRoles$ | async">

这篇关于将值从数组添加到其他数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆