Consume api - Angular

Asked

Viewed 425 times

0

Good night I’m consuming a film api at Angular. However I can not display in the template, the console.log is showing right, but I can not pass the value to template

My Component :

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

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  public filmeId;
  lista= new Object();
  filmes = new Array();
  apiUrl = 'https://api.themoviedb.org/3/movie/top_rated?api_key=13f85672f7128ad9667356e1904e0012&language=pt-BR&page=1';

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.http // get todas os filmes
      .get(this.apiUrl + "filmes/" + this.filmeId + "/filmes", {
        headers: new HttpHeaders({
          'X-Auth-Token': '13f85672f7128ad9667356e1904e0012'
        })
      })
      .subscribe(data => {
        this.lista = data;
        console.log(this.lista);
        this.lista = data;
        // }

      });
  }
}

My Template :

<hr>
<h2>Top Filmes </h2>

<li *ngFor="let f of filmes">
    {{f.id}} {{f.name}}
</li>
  • What appears on console.log?

  • The right movie api appears, with movie id, name, description, etc...

  • Put in question will facilitate!

  • In that part: .subscribe(data => {&#xA; this.lista = data;&#xA; console.log(this.lista);&#xA; this.lista = data;&#xA; // }&#xA;&#xA; }); would not be .subscribe(data =>&#xA; this.filmes = data);?

3 answers

1

apparently this is only happening because you are assigning the supposed array of movies to a variable that is not being informed in the *ngFor="let f of filmes", so try to replace the line this.lista = data; for this.filmes = data;.

1

Are you doing the *ngFor in the empty Movies array. Inside your '.subscribe' you must assign the value of 'date' to the local attribute 'films'.

Thus:

.subscribe(data => {
    this.filmes = data;
    console.log(this.filmes);
}

0

The question is old, but I believe the answer can help someone.

Every http request, at the angle, returns an Observable, and for Observable operations to occur it is necessary to "subscribe" to the obsersavable through the .subscribe(). And through these inscriptions observables "know" when new data were issued.

However, because it is an asynchronous "event" any synchronous logic performed will not work correctly (e.g. code below). Any and all observable data transformation must be either in the method .subscribe() or in the .pipe() (using the RXJS operators).

.subscribe(data => {
        this.lista = data;
        console.log(this.lista);
        this.lista = data; // atribuir valor async para variável sync
        // }

      });

Your code, is not incorrect, but enters the case I commented, you are trying to pass to a synchronous variable (this.lista) an asynchronous value. In some cases this code will work because the request can be completed before the component is rendered, but in the vast majority of cases this does not occur, the request is completed after the component is rendered making the value of this.lista Undefined.

A possible solution would be to move the subscribe location to the template. In this case the list variable would not be required.

Component:

export class HomeComponent implements OnInit {
        observable$: Observable<any>;
        
        ngOnInit():void{
            this.observable$ = this.http.get('api')
              .pipe(aqui pode ser utilizado qualquer operador do rxjs);
        }
    }

Template:

<div *ngFor="let item of observable$ | async as itens">
     <span>{{item | json}}</span>
</div>

Through the async pipe the subscribe is performed and will be shown in the template as soon as the request is completed. And when the Component is destroyed (ngOnDestroy()) pipe will make the automatic unsubscribe.

Another possible solution as well, if you did not want to use asynchronous streams would be through the resolver that will not allow rendering of the component until the requests are completed, and with that, the request data when they are in the component will not be asynchronous (Observables).

Browser other questions tagged

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