我在使用 API 进行 Angular 数据传输时遇到问题

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

在Angular中,我无法将数据从api填充到表中,我认为数据源部分有错误,但我找不到它,当我从控制台跟踪时,我从api中获取数据健康的方式,但是当我转移到桌子上时,桌子也显得空了。

export class List_University {
Id:string;
UniversityName :string;
UniversityDescription :string;
CreatedDate :Date;
UpdateDate :Date;

我遇到对象的服务部分

async read(page: number = 0, size: number = 5, successCallBack?: () => void, errorCallBack?: (errorMessage: string) => void): Promise<{ totalCount: number; university: List_University[] }> {
try {
  const observable = this.httpClientService.get<{ totalCount: number; university: List_University[] }>({
    controller: "university",
    queryString: `page=${page}&size=${size}`
  });

  const data = await firstValueFrom(observable);

  if (successCallBack) {
    successCallBack();
  }
  return data;

} catch (errorResponse) {
  if (errorCallBack) {
    errorCallBack(errorResponse.message);
  }
  throw errorResponse;
}

我使用相关服务的列表组件

    export class ListComponent extends BaseComponent implements OnInit {

  constructor(spinner: NgxSpinnerService, private universityService: UniversityService, private alertifyService: AlertifyService) {
    super(spinner)
  }

  displayedColumns: string[] = ['UniversityName', 'UniversityDescription', 'CreatedDate', 'UpdateDate', 'Delete'];
  dataSource: MatTableDataSource<List_University> = null;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  async getUniversities() {
    this.showSpinner(SpinnerType.BallScaleMultiple);
    const allUniversity: { totalCount: number; university: List_University[] } = await this.universityService.read(
      this.paginator ? this.paginator.pageIndex : 0, this.paginator ? this.paginator.pageSize : 5,
      () => this.hideSpinner(SpinnerType.BallScaleMultiple),
      errorMessage => this.alertifyService.message(errorMessage,
        {
          dismissOther: true,
          messageType: MessageType.Error,
          position: Position.TopRight
        }));
        console.log('Tüm üniversiteler:', allUniversity);
        this.dataSource = new MatTableDataSource<List_University>(allUniversity.university);
        this.paginator.length = allUniversity.totalCount;
        
        console.log('ikinci üniversiteler:', this.dataSource.data);
        
        
      }
      async ngOnInit() {
        await this.getUniversities();
      }
      async pageChanged() {
        await this.getUniversities();
      }

我遇到的html代码

 <div class="mat-elevation-z8">
  <table mat-table [dataSource]="dataSource">

    <ng-container matColumnDef="UniversityName">
      <th mat-header-cell *matHeaderCellDef> UniversityName </th>
      <td mat-cell *matCellDef="let element"> {{element.UniversityName}} </td>
    </ng-container>

    <ng-container matColumnDef="UniversityDescription">
      <th mat-header-cell *matHeaderCellDef> UniversityDescription </th>
      <td mat-cell *matCellDef="let element"> {{element.UniversityDescription}} </td>
    </ng-container>

    <ng-container matColumnDef="CreatedDate">
      <th mat-header-cell *matHeaderCellDef> CreatedDate </th>
      <td mat-cell *matCellDef="let element"> {{element.CreatedDate}} </td>
    </ng-container>

    <ng-container matColumnDef="UpdateDate">
      <th mat-header-cell *matHeaderCellDef> UpdateDate </th>
      <td mat-cell *matCellDef="let element"> {{element.UpdateDate}} </td>
    </ng-container>
    <ng-container matColumnDef="Delete">
      <th mat-header-cell *matHeaderCellDef> Delete </th>
      <td mat-cell *matCellDef="let element"><img src="src\assets\delete.png"> Sil </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
  <mat-paginator (page)="pageChanged()" [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons
    aria-label="Select page of periodic elements">
  </mat-paginator>
</div>

我尝试适当地抛出相关代码,但我认为我的最后一行有问题,我很抱歉,请分享您的宝贵意见并帮助我解决错误

angular datatable datasource
2个回答
0
投票

使用 detectorChanges 确保在异步块中获取数据后重新渲染数据。

readonly cd = inject(ChangeDetectorRef);

async getUniversities() {
        this.showSpinner(SpinnerType.BallScaleMultiple);
    
        const allUniversity: { totalCount: number; university: List_University[] } = await this.universityService.read(
          this.paginator ? this.paginator.pageIndex : 0, this.paginator ? this.paginator.pageSize : 5, () => this.hideSpinner(SpinnerType.BallScaleMultiple),
          errorMessage => this.alertifyService.message(errorMessage,
            {
              dismissOther: true,
              messageType: MessageType.Error,
              position: Position.TopRight
            }));
    
        console.log('Tüm üniversiteler:', allUniversity);
        this.dataSource = new MatTableDataSource<List_University>(allUniversity.university);
        this.paginator.length = allUniversity.totalCount;
    
        console.log('ikinci üniversiteler:', this.dataSource.data);
        this.cd.detectChanges();
      }

0
投票

似乎

await
会以某种方式影响它,因此,尝试删除
await
并使用
.then
并从回调中设置数据:

 async getUniversities() {
    
   this.showSpinner(SpinnerType.BallScaleMultiple);
    this.universityService.read(
          this.paginator ? this.paginator.pageIndex : 0, this.paginator ? this.paginator.pageSize : 5,
          () => this.hideSpinner(SpinnerType.BallScaleMultiple),
          errorMessage => this.alertifyService.message(errorMessage,
            {
              dismissOther: true,
              messageType: MessageType.Error,
              position: Position.TopRight
            })).then((allUniversity: { totalCount: number; university: List_University[] })=>{
    
       console.log('Tüm üniversiteler:', allUniversity);
            this.dataSource = new MatTableDataSource<List_University>(allUniversity.university);
            this.paginator.length = allUniversity.totalCount;
            
            console.log('ikinci üniversiteler:', this.dataSource.data);
            
    
    });  
  }
© www.soinside.com 2019 - 2024. All rights reserved.