0

i found for answer in this site and i get some answer but i don't get to fix my issue. I saw and read many thing here, but nothing.

i'm not getting to populate mat-table with my code. This is my html.

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

     <ng-container matColumnDef="codigo">
       <th mat-header-cell *matHeaderCellDef> Codigo </th>
       <td mat-cell *matCellDef="let oper"> {{oper.operatorId}} </td>
    </ng-container>

    <ng-container matColumnDef="nome">
      <th mat-header-cell *matHeaderCellDef> Nome </th>
      <td mat-cell *matCellDef="let oper"> {{oper.name}} </td>
    </ng-container>

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

When i run my API in the Postman i get this

"itens": [
        [
            {
                "operatorId": "819ee9cc-70b6-44dc-b9e8-afff8705142c",
                "name": "Paulo Correa"
            },
            {
                "operatorId": "ccad3b40-c227-425e-b3b1-feedf6cfac2e",
                "name": "Catarina Silva"
            },
            {
                "operatorId": "68781a7b-ac4c-4a85-9f93-36dc5d65d1af",
                "name": "José da Silva"
            }
        ]
    ],

Ok, my API is working. Component is

import { Component, OnInit } from '@angular/core';
import { OperatorService } from '../operator.service';
import { Operation, Itens } from '../model/operators/operations';

export interface getOperator{
  Id: string;
  Name: string;
}

@Component({
  selector: 'app-operators',
  templateUrl: './operators.component.html',
  styleUrls: ['./operators.component.css'],
  providers: [OperatorService]
})

export class OperatorsComponent implements OnInit {

   displayedColumns: string[] = ['codigo', 'nome'];

    public message: string;
    public dataSource: Itens[];

    constructor( private _operService: OperatorService) 
    {}    

  ngOnInit() {

  this._operService
      .getAll<Operation>()
      .subscribe((data: Operation) => {
        debugger;
        this.dataSource = data.itens;
      });
  }
}

Who is itens? This is my class

export class Operation{
    error: boolean;
    itens: Array<Itens>;
    message: string;
}

export class Itens{
    objectId: string;
    name: string;
}

and my service

    import { Injectable } from '@angular/core';

    import { HttpClient, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
    import { Observable } from 'rxjs';

    import { Configuration } from './app.constants';

    @Injectable({
      providedIn: 'root'
    })
    export class OperatorService {

      private actionUrl: string;

        constructor(private http: HttpClient, private _configuration: Configuration) {
            this.actionUrl = _configuration.ServerWithApiUrl + 'Operators/';
        }

        public getAll<T>(): Observable<T> {
          return this.http.get<T>(this.actionUrl);
      }

      public getSingle<T>(id: number): Observable<T> {
          return this.http.get<T>(this.actionUrl + id);
      }

      public add<T>(itemName: string): Observable<T> {
          const toAdd = JSON.stringify({ ItemName: itemName });

          return this.http.post<T>(this.actionUrl, toAdd);
      }

      public update<T>(id: number, itemToUpdate: any): Observable<T> {
          return this.http
              .put<T>(this.actionUrl + id, JSON.stringify(itemToUpdate));
      }

      public delete<T>(id: number): Observable<T> {
          return this.http.delete<T>(this.actionUrl + id);
      }
    }

@Injectable()
export class CustomInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (!req.headers.has('Content-Type')) {
            req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
        }

        req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
        console.log(JSON.stringify(req.headers));
        return next.handle(req);
    }
}

here is the result from a break point. I have value enter image description here

My data.itens return value, but my mat-table is null or empty. What am i doing wrong?

P.S. here i didn't get to fix: mat-table can't bind dataSource i followed this link Using a static array as datasource for mat-table and i didn't fix this issue.

I have doubt if this thread is duplicate and i'm ban, but all answer that i get didn't fix my issue so i create a new thread about the issue.

EDIT1

I followed an example posted by Antoniossss and the code(component) is this way

import { MatTableDataSource } from '@angular/material/table';

export interface getOperator{
  Id: string;
  Name: string;
}

@Component({
  selector: 'app-operators',
  templateUrl: './operators.component.html',
  styleUrls: ['./operators.component.css'],
  providers: [OperatorService]
})

export class OperatorsComponent implements OnInit {

   displayedColumns: string[] = ['codigo', 'nome'];

    public message: string;
    //public dataSource: Itens[];
    public dataSource=new MatTableDataSource<Itens[]>();

    constructor( private _operService: OperatorService) 
    {}    

  ngOnInit() {

  this._operService
      .getAll<Operation>()
      .subscribe((data: Operation) => {
        debugger;
        this.dataSource.data = data.itens;
      });
  }
}

and this is the error:

[ts] Type 'Itens[]' is not assignable to type 'Itens[][]'. Type 'Itens' is not assignable to type 'Itens[]'. Property 'includes' is missing in type 'Itens'. (property) OperatorsComponent.dataSource: MatTableDataSource

Avinash
  • 1,245
  • 11
  • 19
pnet
  • 258
  • 1
  • 17
  • 1
    My working table for you: https://stackblitz.com/edit/angular-material-table-with-multi-queries?file=app%2Fmembers%2Fmembers.component.ts – Preston Jul 10 '18 at 17:55
  • @Preston, i tried to do like you posted(using my api), but remain the same problem. I don't get error in the console(Chrome), but my table(mat-table) is empty. It's seems that something is missing but i don't know what's. – pnet Jul 10 '18 at 18:48
  • in this line: `.getAll()` is correct? I used type **Operation** and not **any**. Is ok? – pnet Jul 10 '18 at 19:00
  • Typing with a model should work. Not sure if you should have the square brackets in `public dataSource=new MatTableDataSource();` Also, you can fork my StackBlitz and experiment with your code a little at a time until you break mine. – Preston Jul 10 '18 at 19:15
  • i tried with and without brackets and the issue remains. I don't get error, but doesn't fill my table. Will do your complete example with my values(API). – pnet Jul 10 '18 at 19:21
  • Yeah, comment out mine in small sections and insert yours but with my vars and service. You should get an answer quickly. – Preston Jul 10 '18 at 19:23
  • Should be `MatTableDataSource` – Antoniossss Jul 10 '18 at 20:23
  • @Antoniossss, i did this way but doesn't work. It seems that doesn't renderize, cause i have in the table 3 lines but any value printed. I did like Preston said and the error remains. Lack knowledge. – pnet Jul 10 '18 at 21:12

2 Answers2

1

I would do

public dataSource=new MatTableDataSource<Itens>;

and later on

  this._operService
      .getAll<Operation>()
      .subscribe((data: Operation) => {
        this.dataSource.data = data.itens;
      });

Never had problems with tables using this similar snippets.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
0

I solved this way. The json returned from API was wrong. There was an Array inside other Array as shown here:

"itens": [
        [
            {
                "operatorId": "819ee9cc-70b6-44dc-b9e8-afff8705142c",
                "name": "Paulo Correa"
            },
            {
                "operatorId": "ccad3b40-c227-425e-b3b1-feedf6cfac2e",
                "name": "Catarina Silva"
            },
            {
                "operatorId": "68781a7b-ac4c-4a85-9f93-36dc5d65d1af",
                "name": "José da Silva"
            }
        ]
    ],

so the friend that created the api amended it. Now i get to populate my mat-table with data from api. I'm answering to close this post.

pnet
  • 258
  • 1
  • 17