How to use md-table with services in Angular 4

前端 未结 1 639
借酒劲吻你
借酒劲吻你 2020-12-28 20:12

I am quite new in the angular world and i\'m trying to use the new md-table component in Angular Material 2 with Angular 4.

I\'ve made a service from an API which re

相关标签:
1条回答
  • 2020-12-28 20:28

    Here's an example of retrieving data through HTTP: https://plnkr.co/edit/mjQbufh7cUynD6qhF5Ap?p=preview


    You are missing a piece where GroupDatabase does not put any data values on the dataChange stream. It is a BehaviorSubject that starts with an empty array but you do not put any more data on it. This is why the table is only receiving an empty array.

    First, know that ngOnInit will not be called by Angular since GroupDatabase is not a directive and is not part of the change detection cycle.

    Instead, move this.getAllGroups() to the constructor of GroupDatabase. and then subscribe to its result:

    export class GroupDatabase {
      public dataChange: BehaviorSubject<Group[]> = new BehaviorSubject<Group[]>([]);
      get data(): Group[] { return this.dataChange.value }
    
      constructor(groupService: GroupService) {
        groupService.getAllGroups().subscribe(data => this.dataChange.next(data));
      }
    }
    

    Alternatively, get rid of GroupDatabase altogether and have your CustomDataSource directly call your GroupService.

    export class CustomDataSource extends DataSource<Group> {
    
      constructor(
          private _groupService: GroupService, 
          private _paginator: MdPaginator) { }
    
      connect(): Observable<Group[]> {
        const displayDataChanges = [
          this._groupService.getAllGroups(),
          this._paginator.page
        ];
    
        return Observable.merge(...displayDataChanges).map((data, page) => {
          const clonedData = data.slice();
    
          const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
          return data.splice(startIndex, this._paginator.pageSize);
        })
      }
    
      disconnect() {}
    }
    
    0 讨论(0)
提交回复
热议问题