在assets文件夹中,我们有两个名为 1.customers 和 2.appointments 的json文件。 在列表组件中,我正在显示客户列表,如下所示。
这是堆积如山的 DEMO
答案 0 :(得分:1)
您不必在模板中添加过多的逻辑,而是可以轻松地将ContactsService
内的数据合并以满足您的需求。
一个示例是使用combineLatest
获取JSON数据,然后通过约会扩展您的客户。
@Injectable({ providedIn: 'root' })
export class ContactsService {
private appointmentsData$ = this.http.get<IAppointments[]>(APPOINTMENTS_URL);
private customersData$ = this.http.get<ICustomer[]>(CUSTOMERS_URL);
public readonly customers$ = combineLatest(this.appointmentsData$, this.customersData$).pipe(
map(([appointments, customers]) => {
return customers.map(customer =>
{
return {
...customer,
appointments: appointments.filter(appointment =>
{
return appointment.customerIds.indexOf(customer.id) > -1;
})
}
})
})
);
constructor(private http: HttpClient) { }
}
然后,您可以在组件内部使用customers$
观察对象,并使用async
管道在模板内部对其进行迭代:
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent {
public customers$ = this.contactsService.customers$;
constructor(private contactsService: ContactsService) { }
}
<div class="main-div">
<div *ngFor="let customer of customers$ | async">
<p><b>Name:</b> {{customer.name}}</p>
<h3>Appointments</h3>
<ul>
<li *ngFor="let appointment of customer.appointments">
{{ appointment.appointmentName }}
</li>
</ul>
</div>
</div>
答案 1 :(得分:0)
如果像在appointments
中一样,将ListComponent
添加到customers
,则可以在模板中执行以下操作:
<div class="main-div">
<div *ngFor="let customer of customers">
<p><b>Name:</b> {{customer.name}}</p>
<h3>Appointments</h3>
<ul>
<ng-container *ngFor="let a of appointments">
<li *ngIf="a.customerIds.includes(customer.id)">{{a.appointmentName}}</li>
</ng-container>
</ul>
</div>
</div>