Angular material table 使用 graphql 后端的分页

Angular material table pagination with graphql backend

我需要为 angular material table 添加分页。我的数据响应来自 graphql 后端是这样的:

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';

import { MatTableDataSource } from '@angular/material/table';
import { Apollo, gql } from 'apollo-angular';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';



interface Imp_Type {
  uuid: string;
  imp_type_name: string;
  imp_sub_group: string;
  }
  
  interface Response {
    imp_type: Imp_Type[]
  }
  
  const GET_IMP_TYPE = gql`
  query Imp_Type {
    imp_type (limit: 10){
      uuid
      imp_type_name
      imp_sub_group {
        imp_group_id
        sub_grou_name
      }
    }
  }
  `;


@Component({
  selector: 'app-imp-type',
  templateUrl: './imp-type.component.html',
  styleUrls: ['./imp-type.component.scss']
})
export class ImpTypeComponent implements OnInit {

  @ViewChild(MatPaginator) paginator: MatPaginator;

  //imp_type$: Observable<Imp_Type[]>;

  query_data = this.apollo.watchQuery<Response>({
    query:GET_IMP_TYPE
  }).valueChanges.pipe(map(result => result.data.imp_type));

  
  constructor(private apollo: Apollo) { }
  
  displayedColumns: string[] = ['uuid', 'imp_type_name', 'sub_grou_name'];
  dataSource = new MatTableDataSource(this.query_data);
  

  ngOnInit(): void {
   
  }   
}

当我将“query_data”添加到 MatTableDataSource 时出现此错误:

“'Observable<Imp_Type[]>' 类型的参数不能分配给 'unknown[]' 类型的参数。 类型 'Observable<Imp_Type[]>' 缺少类型 'unknown[]' 的以下属性:length、pop、push、concat 和 25 more.ts(2345)"

我该如何解决这个问题?

您必须将 dataSource 分配给 Observablesubscribe 事件,如下所示:

export class ImpTypeComponent implements OnInit {

  @ViewChild(MatPaginator) paginator: MatPaginator;
 
  constructor(private apollo: Apollo) { }
  
  displayedColumns: string[] = ['uuid', 'imp_type_name', 'sub_grou_name'];
  dataSource!: MatTableDataSource<Imp_Type>;
  

  ngOnInit(): void {
    this.apollo.watchQuery<Response>({
      query:GET_IMP_TYPE
    })
    .valueChanges
    .pipe(map(result => result.data.imp_type))
    .subscribe((result: Imp_Type[]) => this.dataSource = new MatTableDataSource(result));
  }   
}