Home > Mobile >  API(get) response(JSON) not display in ngFor - Angular
API(get) response(JSON) not display in ngFor - Angular

Time:05-17

I trying to get a response in JSON of my API and display the values in my Angular page, using a ngFor

I don't have any build errors, the values simply don't display on the page, only in console, using console.log(), so I can't understand.

This is my component.ts:

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-vps',
  templateUrl: './vps.component.html',
  styleUrls: ['./vps.component.scss'],
})

export class VpsComponent implements OnInit {
  vpsOptions: any;
  baseUrl: string = "http://127.0.0.1:8000/"
  valor: number = 555;
  tipo: any = "mês";

ngOnInit(): void {
   this.getVps()
   console.log("ngOnInit")
   console.log(this.vpsOptions)
}

constructor(private httpClient: HttpClient) {
    this.vpsOptions = []
}
public getVps() {
 this.httpClient.get(this.baseUrl 'vps').subscribe((result:any) =>{
  for(let item in result){
   this.vpsOptions.push(result[item]);
  }
});

This is my component.html:

<ng-container *ngFor="let vps of vpsOptions">
      <div >
        <div >
          <div >
            <h3 >{{vps.nome}}</h3>
          </div>
          <div >
            <div >
              <p >
                <span > R$ <span >{{valor}},00</span>/{{tipo}}</span> <br>
                <span >**Preço na contratação de 48 meses </span><br>
                {{vps.processador}} <br>
                {{vps.memoria}} <br>
                {{vps.disco1}} de Armazenamento <br>
                {{vps.banda}} de Banda <br>
                {{vps.ips}} IP(s) dedicado(s) <br>
                100% Acesso Root <br>
                100Mb/s Rede <br>
                Suporte 8/5 <br> <br>
                <button type="submit"  style="background-color: #213B89;"
                >Solicitar Orçamento</button>
                <!-- <a  href="">Veja todas as caracterísicas</a> -->
              </p>
            </div>
          </div>
        </div>
      </div>
</ng-container>

This is my response API(I'm using fastAPI of Python):

API RESPONSE

This is the response in console of browser: CONSOLE LOG BROWSER

CodePudding user response:

your vpsOptions should be an observable

in your ts you should do:

vpsOptions$: new Observable<any>;

 ...

ngOnInit(): void {
   this.vpsOptions$ = this.getVps()
   ...
}

or more cleaner way:

vpsOptions$ = this.getVps();

...

and then in your template you can do:

<ng-container *ngFor="let vps of (vpsOptions$ | async)">
    ...your content
</ng-container>

this is.

good luck an enjoy angular!

CodePudding user response:

I refactored my code and create other classes to abstract some functions, to be more practice.

I created an interface.ts, to format my get:

export interface Vps{
  id?: number;
  nome?:string;
  ...

I created a service.ts, to abstract the httpClient.get() function:

import { Vps } from './vps.interface';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })

export class VpsService {
  private readonly baseUrl: string = "http://127.0.0.1:8000/"
  constructor(private httpClient: HttpClient) {}

  getVps(): Observable<Vps[]> {
    const url = this.baseUrl 'vps';
    return this.httpClient.get<Vps[]>(url);
  }
}

Thanks @Dario for the answer, I used and Observable<Vps[]>: //declaring the object

vpsOptions: Observable<Vps[]>;

//Initializing the object calling the service.ts

constructor(private vpsService: VpsService) {
    this.vpsOptions = this.vpsService.getVps();
  }

//Finally, I changed the component.html to receive the object(Observable) correctly

<ng-container *ngIf="vpsOptions | async as options">
    <ng-container *ngFor="let option of options">
         <!-- my display logic here -->
     </ng-container>
</ng-container>
  • Related