Angular,如何从嵌套的 rest api 获取数据并查看材料表中的数据

问题描述 投票:0回答:0

我想从嵌套的rest api获取数据并在材料表的视图数据中查看数据。 我该如何解决这个问题? 我该如何解决这个问题? 我该如何解决这个问题? 我该如何解决这个问题? 我该如何解决这个问题?

  • 来自网址的API:
{
list: [
       {
        id: 1,
        login: "[email protected]",
        first_name: "AK",
        phone: "967777777777",
       },
       {
        id: 2,
        login: "[email protected]",
        first_name: "QR",
        phone: "967777777777",
       },
       {
        id: 3,
        login: "[email protected]",
        first_name: "JM",
        phone: "967777777777",
       }
      ],
count: 3,
success: true
}
  • interface-1 ( users.ts ):
import { List } from "./list"

export interface Users {
    list: List[]
    count: number
    success: boolean
  }
  • interface-2 ( list.ts ):
export interface List {
    id: number
    first_name: string
    login: string
    phone: string
}
  • user.service.ts
getUsers(): Observable<Users[]>{
    //myHeader = myHeader.set('id', '123456');
    return this.http.get<Users[]>(`https://yapi.yementrack.com.ye/panel/user/list`).pipe(
      tap(users => console.log(users)),
    );
  }
  • users.component.ts:
import { Component, OnInit } from '@angular/core';
import { UsersService } from '../../services/users.service';
import { MatTableDataSource } from '@angular/material/table';
import { Posts } from 'src/app/interface/posts';

export class UsersComponent implements OnInit{
  displayedColumns: string[] = ['id', 'first_name', 'login', 'phone'];
  users: any[] = [];

  constructor(private usersService: UsersService){ }

  ngOnInit(): void {
    this.onGetUsers();
  }

  onGetUsers(): void{
    this.usersService.getUsers().subscribe(
      (response => {
        this.users = new MatTableDataSource<Posts>(response);
      })
    );
  }

}
  • users.component.html:
<table mat-table [dataSource]="users" class="mat-elevation-z8">
  
     Position Column 
    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef> ID </th>
      <td mat-cell *matCellDef="let element"> {{element.id}} </td>
    </ng-container>

    <ng-container matColumnDef="first_name">
      <th mat-header-cell *matHeaderCellDef> first_name </th>
      <td mat-cell *matCellDef="let element"> {{element.first_name}} </td>
    </ng-container>
  
    <ng-container matColumnDef="login">
      <th mat-header-cell *matHeaderCellDef> login </th>
      <td mat-cell *matCellDef="let element"> {{element.login}} </td>
    </ng-container>
  
    <ng-container matColumnDef="phone">
      <th mat-header-cell *matHeaderCellDef> phone </th>
      <td mat-cell *matCellDef="let element"> {{element.phone}} </td>
    </ng-container>
  
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
angular api angular-http angular-material-table
© www.soinside.com 2019 - 2024. All rights reserved.