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

Asked

Viewed 1,294 times

0

It is returning normally from the database, but when it passes to datasource it is 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 inserir a descrição da imagem aqui

HTML:

<div class="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]);
      });
  }
}
  • post your html.

  • Edited with html now

  • Are there any errors in the console? It seems that the variables name is different from your html interface

  • no, no errors, but I suspect it has to do with the type of data that this table expects, because the table of the material angular expects a datasource,: link , I use with filters

  • This is okay but for example your interface has no name field or lvl

  • this was just a test,nothing appears,if I put only element appears Object,but qnd I put the nometcp for example n appears nothing,already tested the observable,it ta populated,but qnd it will pass to datasource it seems q gets Undefined,n got it right

  • What is the return of tcps there on getTcpUpdateListener()? It is returning an Obsevable?

  • Services posted also

Show 3 more comments

1 answer

1


It worked for me this way:

@ViewChild(MatTable) public matTable;

updateDataSource(data) {
   this.dataSource = new MatTableDataSource<any>(data);
   this.matTable.renderRows();
}
  • 1

    The render Rows did not work, but the top line solved the problem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.