Home > Net >  Error says that 'ERROR TypeError: data.slice is not a function'
Error says that 'ERROR TypeError: data.slice is not a function'

Time:02-23

I have already looked into some questions like this but none of them were useful on my case. I'm receiving a obj that returns a list of cities with their names, habitants and states. Here's my http service request:

cidadesUrl = 'http://localhost:8080/api/cidades';

  constructor(private http: HttpClient) { }

  listar(): Observable<Cidade[]>{
    return this.http.get<Cidade[]>(this.cidadesUrl);
  }

and here's the calling to the service:

  cidades!: Cidade[];

  constructor(private cidadeService:CidadeService) { }

  listar(){
    this.cidadeService.listar().subscribe(data => { this.cidades = data });
    console.log(this.cidades);
  }

and my html:

<p-table [value]="tabela" [paginator]="true" [rows]="4" responsiveLayout="scroll">
  <ng-template pTemplate="header">
      <tr>
          <th>Nome</th>
          <th>Habitantes</th>
          <th>Estado</th>
          <th>Ações</th>
      </tr>
  </ng-template>
  <ng-template pTemplate="body" let-cidade>
      <tr>
          <td>{{cidade.nome}}</td>
          <td>{{cidade.qtdHabitantes | number}}</td>
          <td>{{cidade.estado}}</td>
          <td >
            <button pButton icon="pi pi-pencil" pTooltip="Editar" tooltipPosition="top"></button>
            <button pButton  icon="pi pi-trash"  pTooltip="Excluir" tooltipPosition="top"></button>
          </td>
      </tr>
  </ng-template>
</p-table>

Tabela variable:

@Input() tabela: Cidade[] = [];

I don't know why but when the page loads, i get the error:

ERROR TypeError: data.slice is not a function
    at Table.get dataToRender [as dataToRender] (primeng-table.mjs:398)
    at Table_table_7_Template (primeng-table.mjs:1840)
    at executeTemplate (core.mjs:9618)
    at refreshView (core.mjs:9484)
    at refreshEmbeddedViews (core.mjs:10609)
    at refreshView (core.mjs:9508)
    at refreshComponent (core.mjs:10655)
    at refreshChildComponents (core.mjs:9280)
    at refreshView (core.mjs:9534)
    at refreshComponent (core.mjs:10655)

When I open the Network tab in console, the cities are there, but they dont show up in the table ![enter image description here

I dont know what could be possibly generating this error. Hoping someone can help

CodePudding user response:

I believe this error has to do with the list being undefined:

ERROR TypeError: data.slice is not a function

You would need to set initial state, maybe something like this:

@Input() tabela!: Cidade[] = [];

The exclamation ! tells TS to assume a value has been set and it is not undefined but this may not be a valid assumption at compile time.

CodePudding user response:

You can try to inizialize tabela property like

@Input() tabela: Cidade[] = [];

Looks like the table is trying to access tabela but it is not the kind of data it's expecting

  • Related