Luiz Mitidiero
Luiz Mitidiero

Reputation: 1171

How to use Angular Material Table Component with Paginator integrated to back-end?

I have an Angular Material Table Component and I wanna integrate it with my back-end server. I could do it for the initial request outside my DataSource.

I'm implementing the method connect in my DataSource, but I didn't get success reaching the data from backend on this method. Is it the correct method? If yes, how can I implement it? If no, what is the best method to fetch data from the server in my DataSource? This following last try resulted in an infinite loop adding data to my table

  connect(): Observable<any> {
    const displayDataChanges = [
      this._exampleDatabase.dataChange,
      this._paginator.page,
      this._sort.mdSortChange
    ];

    return Observable.merge(...displayDataChanges).map(() => {
      let currentData = null;

      const startIndex = this._paginator.pageIndex * this._paginator.pageSize;

      return this.studentService.query()
        .subscribe(data => {
          currentData = data.students;
          return currentData;
        });

    });
  }

Upvotes: 1

Views: 423

Answers (1)

Luiz Mitidiero
Luiz Mitidiero

Reputation: 1171

I finally got a solution.

connect(): Observable<Student[]> {
    //events to listen
    const displayDataChanges = [
      this._sort.mdSortChange,
      this._paginator.page,
      this._filterChange,
    ];

    // If the user changes the sort order, reset back to the first page.
    this._sort.mdSortChange.subscribe(() => {
      this._paginator.pageIndex = 0;
    });

    return Observable.merge(...displayDataChanges)
      .startWith(null)
      .switchMap(() => {
        //call the service method which should return the data
        return this.studentService.query(this._paginator.pageIndex);
      })
      .catch(() => {
        // Catch exceptions
        return Observable.of(null);
      })
      .map(result => {
        // Flip flag to show that loading has finished.
        this.isLoadingResults = false;
        return result;
      })
      .map(result => {
        if (!result) { return []; }

        //set results length (for pagination reasons)
        this.resultsLength = result.tableData.total;

        //return fetched data
        return result.students;
      });

  }

Upvotes: 1

Related Questions