根据另一个服务的ID检索一个服务的ID值

时间:2020-08-07 01:28:00

标签: angular

我正在编写一个有角度的应用程序,用于检索包含客户名称的工作。在将数据存储在作业表中时,我正在存储customerId。因此,JobModel包含CustomerId。

在我的有角度的工作组件中,我正在注入客户和工作服务。我需要根据Jobservice返回的CustomerId从客户服务中检索客户名称。

我该如何实现

组件

constructor(
    private customerService: CustomerService,
    private jobService: JobService) { }

  ngOnInit() {
    this.customerService.GetCustomers().subscribe(customers => this.customers = customers);
    this.jobService.GetJobs().subscribe(jobs => this.jobs = jobs);
  }

HTML

<h2>Jobs list</h2>
<table spacing="0">
  <thead>
    <tr>
      <th>Customer</th>
      <th>When</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let job of jobs">
      <td>{{job.customer}}</td>
      <td>{{job.when | date:'shortDate'}}</td>
      <td>
        <a [routerLink]="['/job', job.jobId]">Open</a>
      </td>
    </tr>
  </tbody>
</table>

型号

export interface JobModel {
  jobId: number;
   customerId: number;
  when: Date;
}

客户

export interface CustomerModel {
  customerId: number;
  name: string;
  type: string;
}

1 个答案:

答案 0 :(得分:0)

我猜想您要在工作中使用客户的姓名。我会尝试这样的事情:

this.jobs.forEach((job) => {
  job.customerName = this.customers.find((customer) => customer.customerId === job.customerId).name;
});

编辑:使用来自rxjs的zip:

import { zip } from 'rxjs';
...
zip(this.customerService.GetCustomers(), this.jobService.GetJobs()).subscribe([customers, jobs] => {
    this.customers = customers;
    this.jobs = jobs;
    this.jobs.forEach((job) => {
      job.customerName = this.customers.find((customer) => customer.customerId === job.customerId).name;
    });
});