首页 > 解决方案 > 使用Angular显示外键值而不是键

问题描述

我创建了两 (2) 个表 1. 服务:名称,service_type(来自 service_type 的 ID) 2. service_type:id,名称

我正在使用 Angular7 从 Laravel API 获取端点。我想从 service_type 表中显示名称(值而不是键)。services 是主表。

我已经创建了 model.ts、service.ts component.ts 和 component.html

模型

export class Services {
    _id: string;
    name: string;
    service_type: number;
  }

服务

  getServices (): Observable<Services[]> {
    return this.http.get<Services[]>(apiUrl)
      .pipe(
        tap(services => console.log('Fetch services')),
        catchError(this.handleError('getServices', []))
      );
  }

  getService(id: number): Observable<Services> {
    const url = `${apiUrl}/${id}`;
    return this.http.get<Services>(url).pipe(
      tap(_ => console.log(`fetched service id=${id}`)),
      catchError(this.handleError<Services>(`getService id=${id}`))
    );
  }

组件.ts

  displayedColumns: string[] = ['name', 'service_type'];  
  data: Services[] = [];
  isLoadingResults = true;  

  constructor(private api: ServicesService) { }

  ngOnInit() {

    this.api.getServices()
      .subscribe(res => {
        this.data = res;
        console.log(this.data);
        this.isLoadingResults = false;
      }, err => {
        console.log(err);
        this.isLoadingResults = false;
      });

组件.html

      <tr  *ngFor="let datas of data">
          <td>{{datas.name}}</td>
          <td>{{datas.service_type}}</td>
        <td>

{{datas.service_type}}

它来自另一个名为 service_type 的表,我想显示值(名称)而不是键(id)

标签: angularlaravelapi

解决方案


推荐阅读