Angular 11 get specific data from API and display on mat-table

Viewed 1088

I want to get specific data from API and display the data to Angular material table. Here's example data from the API

{ "id": 0, "branchCode": "JKT", "tableName": "PRODUCT", "requestedDate": "2021-01-04T02:37:07.205Z", "createdDate": "2021-01-05T02:37:07.205Z", "createdBy": "jans" }

It's just one of many data from the API I use. I want to get the branchCode data, and display each of them to the table header using Angular material table. I already try it, but it's not displayed what I wanted.

Here's my service.ts

import { Injectable } from "@angular/core";
import { environment } from "@environments/environment";
import { Sync } from "@models/sync/sync.model";
import { endpoint } from "@models/endpoint.const";
import { PagingRequest } from "@models/paging-request.model";
import { RequestResponse } from '@models/request-response.model';
import { Observable } from "rxjs";
import { map } from "rxjs/operators";

import { RESTService } from '../rest.service';

@Injectable({
    providedIn: 'root'
})

export class SyncService {
    constructor(private rest: RESTService) { }

    list(paging: PagingRequest): Observable<any> {
        let request: RequestResponse<PagingRequest> = new RequestResponse<PagingRequest>(paging);
        
        return this.rest.post<any>(`${environment.apiUrl}${endpoint.sync.view_list}`, request).pipe(map(
            response => {
                return response.body.data;
            }
        ));
    }
}

My datasource.ts

import { CollectionViewer, DataSource } from "@angular/cdk/collections";
import { Sync } from "@models/sync/sync.model";
import { PagingRequest } from "@models/paging-request.model";
import { SyncService } from "@services/sync/sync.service";
import { of } from "rxjs";
import { Observable, BehaviorSubject } from "rxjs";
import { catchError } from "rxjs/operators";

export class SyncDataSource implements DataSource<Sync> {
    syncSubject = new BehaviorSubject<Sync[]>([]);
    countSubject = new BehaviorSubject<number>(0);

    constructor(private syncService: SyncService) { }

    connect(collectionViewer: CollectionViewer): Observable<Sync[]> {
        return this.syncSubject.asObservable();
    }

    disconnect(collectionViewer: CollectionViewer): void {
        this.syncSubject.complete();
    }
    
    loadData(paging: PagingRequest) {
        this.syncService.list(paging).pipe(
            catchError(() => of([])),
        )
            .subscribe(async resp => {
                this.countSubject.next(resp.totalElements);
                this.syncSubject.next(resp.content);
            });
    }
}

My component.ts

import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { SyncService } from '@services/sync/sync.service';
import { EditMode } from '@models/edit-mode.const';
import { Router } from '@angular/router';
import { PagingRequest } from '@models/paging-request.model';
import { SyncDataSource } from './sync-list.datasource';
import { Sync } from '@models/sync/sync.model';
import { Subject, Subscription } from 'rxjs';
import { SharedService } from '@services/shared.service';
import { SelectionModel } from '@angular/cdk/collections';

@Component({
  selector: 'app-sync-list',
  templateUrl: './sync-list.component.html',
  styleUrls: ['./sync-list.component.scss']
})
export class SyncListComponent implements OnInit, OnDestroy {
  private subscription: Subscription[] = [];

  displayedColumns: string[] = ['tableName', 'branchCode'];
  dataSource: SyncDataSource;
  keyword: string = '';
  selection = new SelectionModel<Sync>(true, []);

  resultsLenght = 0;

  @ViewChild(MatPaginator) paginator: MatPaginator;

  mode = EditMode.list;
  title = "Sync List";
  currentUrl = '';

  constructor(
    private syncService: SyncService, 
    private router: Router, 
    private sharedService: SharedService) { }

  ngOnDestroy(): void {
    this.subscription.forEach((sb => sb.unsubscribe()));
  }

  ngOnInit(): void {
    this.currentUrl = this.sharedService.removeLastPageUrl(this.router.url);

    let pagingParam: PagingRequest = new PagingRequest();
    
    this.dataSource = new SyncDataSource(this.syncService);
    this.dataSource.loadData(pagingParam);

    const sb = this.dataSource.countSubject.subscribe(count => {
      this.resultsLenght = count;
    });
    this.subscription.push(sb);
  }

  loadData() {
    let pagingParam: PagingRequest = new PagingRequest();

    pagingParam.keyword = this.keyword;
    pagingParam.page = this.paginator.pageIndex + 1;
    pagingParam.size = this.paginator.pageSize;
    this.dataSource.loadData(pagingParam);
    this.selection.clear();
  }

}

And component.html

<div class="example-preview">
    <div class="example-container mat-elevation-z8">
        <div class="example-header">
            <h1>{{ title }}</h1>
        </div>
    </div>
</div>

<div class="example-preview">
    <div class="example-container mat-elevation-z8">
        <div class="example-header">
            <table mat-table [dataSource]="dataSource">
                <ng-container matColumnDef="tableName">
                    <th mat-header-cell *matHeaderCellDef>Name</th>
                    <td mat-cell *matCellDef="let row"
                    [ngClass]="row.isDeleted == true ? 'deleted-data' : ''">{{ row.tableName }}</td>
                </ng-container>

                <ng-container matColumnDef="branchCode">
                    <th mat-header-cell *matHeaderCellDef>Code</th>
                    <td mat-cell *matCellDef="let row"
                    [ngClass]="row.isDeleted == true ? 'deleted-data' : ''">{{ row.branchCode }}</td>
                </ng-container>
                
                <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
                <tr class="row-hover" mat-row *matRowDef="let row; columns: displayedColumns;"></tr>

                <!-- Row show when no data found -->
                <tr class="mat-row" *matNoDataRow>
                    <td class="mat-cell" colspan="4">No Data Available</td>
                </tr>
            </table>
        </div>
    </div>
</div>

Please Help me. I'm new on Angular. Thank you.

0 Answers
Related