首页 > 解决方案 > Angular - 使用模型中的计算属性

问题描述

我们正在开发一个具有以下模型的应用程序:

interface IEmployee{
    firstName?: string;
    lastName?: string;
}

export class Employee implements IEmployee{
    public firstName?: string;
    public lastName?: string;

    constructor(data: object | Employee) {
        Object.assign(this, data);
    }

    get displayName(): string {
        return this.firstName + ' ' + this.lastName;
    }
}

我们有另一个模型 -Department它引用了 Employee 类,如下所示:

interface IDepartment{
    id?: string;
    name?: string;
    employees[]: Employee;
}

我们在项目的两个实例中进行了两次 API 调用——一个用于获取用户,另一个用于获取部门。在获取员工时,我们可以获取displayName使用以下代码填充的员工:

      this.http.get<Employee[]>(`${this.apiURL}\employees`)
      .pipe(map(response => {
        return response.map(data => new Employee(data));
      }));

在获取部门时,有什么方法可以为所有员工填充员工显示名?

标签: angulartypescript

解决方案


您可以使用combineLatest,您可以在其中为输入定义 N 个可观察对象,例如:

combineLatest([departments$, employee$])
  .pipe(
     map(([departments, employee]) => /* do awesome staff */ )
  );

如果两者都发出值,则 map 将执行


推荐阅读