How to transform the json observable into datasource for Angular Material 2

0

This is usually returning from the database, but when it passes the datasource it becomes empty

component

import { Component, OnInit} from '@angular/core';
import { Tcp } from '../tcp';
import { TcpService } from '../../services/tcp.service';
import { MatTableDataSource } from '@angular/material';
import { Subscription } from 'rxjs';



@Component({
  selector: 'app-tcp',
  templateUrl: './tcp.component.html'
})
export class TcpComponent implements OnInit {
    tcps:Tcp[]=[];
    private tcpSub:Subscription;
    public dataSource:MatTableDataSource<Tcp>;
    constructor(public tcpS: TcpService){
    }
  ngOnInit() {
    this.tcpS.getTcps();
    this.tcpSub = this.tcpS.getTcpUpdateListener().subscribe((tcps:Tcp[]) => {
      this.tcps = tcps;
      this.dataSource = new MatTableDataSource(this.tcps);
    });
  }
  displayedColumns: string[] = ['name', 'reg', 'lvl'];



  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}
export interface Tcp {
     nometcp:string;
     regtcp:Number;
     niveltcp:Number;
}

When you start to render the table with the number of records

HTML:

<divclass="navy">
    <nav class="navbar navbar-default">
            <div class="container-fluid">
              <!-- Brand and toggle get grouped for better mobile display -->

              <!-- Collect the nav links, forms, and other content for toggling -->
              <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <li routerLinkActive="active"><a [routerLink] = "['/home']">Home</a></li>
                    <li class="active" routerLinkActive="active"><a [routerLink] = "['/TCP']">TCP</a></li>
                    <!-- <li routerLinkActive="active"><a [routerLink] = "['/user']">Users</a></li> -->
                    <li routerLinkActive="active"><a [routerLink] = "['/os']">Ordem De Serviço</a></li>
                    <li routerLinkActive="active"><a [routerLink] = "['/produtos']">Produtos</a></li>
                </ul>

                <ul class="nav navbar-nav navbar-right">
                    <li routerLinkActive="active"><a [routerLink] = "['/']" (click)="logout()">Logout</a></li>
                </ul>
              </div><!-- /.navbar-collapse -->
            </div><!-- /.container-fluid -->
          </nav>
</div>
<div class="container">
<div> <a routerLinkActive="active" [routerLink] = "['/TCPc']" class="btn btn-primary btn-success"><span class="glyphicon glyphicon-plus"></span> Criar</a> </div>
<br>  
<div class="row">
    <mat-form-field>
        <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
      </mat-form-field>

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

        <!-- Name Column -->
        <ng-container matColumnDef="name">
          <th mat-header-cell *matHeaderCellDef> Nome </th>
          <td mat-cell *matCellDef="let element"> {{element.name}} </td>
        </ng-container>

        <!-- Weight Column -->
        <ng-container matColumnDef="reg">
          <th mat-header-cell *matHeaderCellDef> Registro </th>
          <td mat-cell *matCellDef="let element"> {{element.nometcp}} </td>
        </ng-container>

        <!-- Symbol Column -->
        <ng-container matColumnDef="lvl">
          <th mat-header-cell *matHeaderCellDef> Nivel </th>
          <td mat-cell *matCellDef="let element"> {{element.lvl}} </td>
        </ng-container>

        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
      </table>

</div>
  </div>

Services

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Tcp } from '../tcp/tcp';
import { Subject } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class TcpService {
  private tcps: Tcp[] = [];
  private tcpsUpdated = new Subject<Tcp[]>();

  uri = 'http://localhost:3000/api/tcps';

  constructor(private http: HttpClient) { }

  getTcps(){
    this.http
      .get<{ message: string; tcps: any }>(
        this.uri
      )
      .pipe(map((tcpData) => {
        return tcpData.tcps.map(tcp => {
          return {
            registro: tcp.regtcp,
            nivel: tcp.niveltcp,
            nome: tcp.nometcp,
            id: tcp._id
          };
        });
      }))
      .subscribe(transformedTcps => {
        this.tcps = transformedTcps;
        this.tcpsUpdated.next([...this.tcps]);
      });
  }

  getTcpUpdateListener() {
    return this.tcpsUpdated.asObservable();
  }

  addTcp(nometcp: string, regtcp: Number,niveltcp:Number) {
    const tcp: Tcp = { id: null, nometcp: nometcp, regtcp: Number(regtcp),niveltcp: Number(niveltcp) };
    this.http
      .post<{ message: string, tcpId: string }>(this.uri, tcp)
      .subscribe(responseData => {
        const id = responseData.tcpId;
        tcp.id = id;
        this.tcps.push(tcp);
        this.tcpsUpdated.next([...this.tcps]);
      });
  }

  deleteTcp(tcpId: string) {
    this.http.delete(this.uri + tcpId)
      .subscribe(() => {
        const updatedTcps = this.tcps.filter(tcp => tcp.id !== tcpId);
        this.tcps = updatedTcps;
        this.tcpsUpdated.next([...this.tcps]);
      });
  }
}
    
asked by anonymous 01.09.2018 / 15:53

1 answer

1

It worked for me this way:

@ViewChild(MatTable) public matTable;

updateDataSource(data) {
   this.dataSource = new MatTableDataSource<any>(data);
   this.matTable.renderRows();
}
    
21.09.2018 / 05:07