【问题标题】:How to get the objects of the other API?如何获取其他 API 的对象?
【发布时间】:2019-02-21 18:44:07
【问题描述】:

在assets 文件夹中,我们有两个名为1.customers 和2.appointments 的json 文件。 在 List 组件中,我正在显示客户列表,如下所示。

现在我想显示该特定客户的约会,如下所示。

这里是堆栈闪电战DEMO

【问题讨论】:

    标签: angular typescript angular7


    【解决方案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$ observable 并使用 async-pipe 在你的模板中迭代它:

    @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>  
    

    DEMO

    【讨论】:

      【解决方案2】:

      如果您将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> 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-12-02
        • 1970-01-01
        • 2019-09-05
        • 1970-01-01
        • 2023-04-04
        • 2021-12-21
        • 1970-01-01
        相关资源
        最近更新 更多