0

I'm working with Angular 12 and I'm creating a CRM. What I want to do is to display my APIs in an Angular table component.

My Postman APIs are like this:

{

        "content": [
            {
                "id": 1,
                "ragioneSociale": "Bruno-Romano SPA - EDIT",
                "partitaIva": "14812266616",
                "tipoCliente": "SRL",
                "email": "rosalino.caruso@gmail.com",
                "pec": "antonio.damico@gmail.com",
                "telefono": "+38 855 62 44 5685",
                "nomeContatto": "Sarita",
                "cognomeContatto": "Serraaa",
                "telefonoContatto": "380.260.3225",
                "emailContatto": "armando.martinelli@hotmail.com",
                "indirizzoSedeOperativa": {
                    "id": 2,
                    "via": "Contrada Gastone 4, Piano 4",
                    "civico": "698",
                    "cap": "38615",
                    "localita": "Vania del friuli",
                    "comune": {
                        "id": 1,
                        "nome": "LASTRA A SIGNA",
                        "provincia": {
                            "id": 1,
                            "nome": "FIRENZE",
                            "sigla": "FI"
                        }
                    }
                },
                "indirizzoSedeLegale": {
                    "id": 1,
                    "via": "Strada Ricci 55, Appartamento 58",
                    "civico": "925",
                    "cap": "65995",
                    "localita": "Ivonne umbro",
                    "comune": {
                        "id": 1,
                        "nome": "LASTRA A SIGNA",
                        "provincia": {
                            "id": 1,
                            "nome": "FIRENZE",
                            "sigla": "FI"
                        }
                    }
                },
                "dataInserimento": "2019-06-01T08:11:01.911+00:00",
                "dataUltimoContatto": "2021-03-24T21:32:06.375+00:00",
                "fatturatoAnnuale": null
            }, 
    etc...
/* THE INTERCEPTOR - just in case */

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpResponse,
  HttpErrorResponse,
  HttpInterceptor
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, tap, finalize } from 'rxjs/operators';

@Injectable()
export class MyHttpInterceptorInterceptor implements HttpInterceptor {
  constructor() {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   let ok: string;
   let beaererAuth = 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImlhdCI6MTYyODU4NzM5NSwiZXhwIjoxNjI5NDUxMzk1fQ.Kgjk49NPzvTgLxBbDTzV8LT0efnNqiiHjLOvcdI1nSkhckzfqKI0GBdN1aFwlU7MOOCeqMvg9U_IXYWksSFuNA';
    
   let authReq: HttpRequest<any> = req;
   authReq = req.clone({ headers: 
    req.headers.set("Authorization", 'Bearer ' + beaererAuth)
                          .set("X-TENANT-ID", 'fe_0321')

   });
   console.log(authReq);
   
   
   return next.handle(authReq).pipe(
     tap(
       event => {ok = event instanceof HttpResponse ? 'succeeded' : '' },
       error => { }
     ),
     catchError((error: HttpErrorResponse) => {
       return throwError(error);
     }),
     finalize(() => {  })
   );
  }
}
/* THE SERVICE*/

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

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

  private urlUsersAPI = 'https://epicode.online/epicodebeservice_v2/api/clienti?page=0&size=20&sort=id,ASC';

  constructor(private http: HttpClient) { }

  getAllUsers() {
    return this.http.get(this.urlUsersAPI);
  }

  getUsers(id: number) {
    return this.http.get(this.urlUsersAPI+id);
  }

  deleteUser(userId: number) {
    return this.http.delete(this.urlUsersAPI+userId);
  }

  updateUser(user: any) {
    return this.http.put(this.urlUsersAPI+user.id, user);
  }

  createUser(user: any) {
    return this.http.post(this.urlUsersAPI, user);
  }
}
/* THE TABLE */ 

<app-header></app-header>
<div class="container">
<h1>LISTA CLIENTI</h1>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8 demo-table">
    <!-- Position Column -->
    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef> ID </th>
      <td mat-cell *matCellDef="let element"> {{element.id}} </td> 
    </ng-container> 


     <!-- Symbol Column -->
     <ng-container matColumnDef="action">
        <th mat-header-cell *matHeaderCellDef>  </th>
        <td mat-cell *matCellDef="let element"> 
          <button (click)="selectEditUsers(element)" mat-icon-button color="primary">
            <mat-icon>edit</mat-icon>
        </button>
            <button (click)="removeUsers(element)" mat-icon-button color="warn">
                <mat-icon>cancel</mat-icon>
            </button> 
        </td>
    </ng-container>
  
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
  </div>
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

0

Laura, you can choose two approach

1.-your API return all the elements in a call

You only need use the "dataSource" of the table material. You can use as dataSource an array or even an observable, so, if you inject your service in the constructor of the component

//in you component

userData$=this.userService.getAllUsers().pipe(
          map(x=>x.content) //<--only want the "content"
) 
constructor(private userService:UserService){}

and

<table mat-table [dataSource]="userData$ |async">
...
</table>

But pay attention your code and your API, It's looks like your API expect one kind of pagination

2.-Use a mat-table and a mat-paginator like this SO, but you need another API that give you the number of "users" you has

NOTE: See the docs to know how work with a mat-data-table (your columns should has as name the columns and elements you receivd)

Eliseo
  • 50,109
  • 4
  • 29
  • 67