Search code examples
angulargetthemoviedb-api

Fetch data from API, problem first time array is undefined


I have a issue fetching data from API, I fetch from API when I submit a form. The issue is when I console log the array to see what elements I receive, my array is undefined, and it's only when I click (submit the form) the second time that the array contains the data. I try to console the array in my submitForm function in the component movie that you can see I the code.

Screen of my console displaying the issue

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Subject, Observable, pipe } from "rxjs";
import { Movie } from "../models/movie.model";
import { map } from "rxjs/operators";
import { TvShow } from '../models/tvShow.models';

@Injectable({
  providedIn: "root",
})
export class SearchService {
  token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

  constructor(private httpClient: HttpClient) {}

  searchMovie(title): Observable<Movie[]> {
    return this.httpClient
    .get<Movie[]>(
        "https://api.themoviedb.org/3/search/movie?api_key=" +
          this.token +
          "&language=fr&query=" +
          title
      )
      .pipe(map((response: any) => response.results));
  }
}

works the second time that I submit the form.

<div class="search">
  <form class="form-inline" [formGroup]="movieForm" (ngSubmit)="submitForm()">
    <input type="text" id="title" class="form-control form-control-lg" formControlName="title"
      placeholder="Search for a movie">
    <button type="submit" class="btn btn-primary" [disabled]="movieForm.invalid">Search</button>
  </form>
</div>
<app-list *ngFor="let movie of movies; let i = index" [indexOfMovie]="i" [movie]="movie">
</app-list>

import { Component, OnInit } from "@angular/core";
import { Movie } from "src/app/models/movie.model";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { SearchService } from "src/app/services/search.service";

@Component({
  selector: "app-movie",
  templateUrl: "./movie.component.html",
  styleUrls: ["./movie.component.scss"],
})
export class MovieComponent implements OnInit {
  movies: Movie[];
  movieForm: FormGroup;


  constructor(
    private searchService: SearchService,
    private formBuilder: FormBuilder
  ) {}

  ngOnInit(): void {
    this.initForm();
  }


  initForm() {
    this.movieForm = this.formBuilder.group({
      title: ["", Validators.required],
    });
  }

  submitForm() {
    const formValue = this.movieForm.value;
    const movieSearch = formValue["title"];

    this.searchService
      .searchMovie(movieSearch)
      .subscribe((res) => (this.movies = res));

    console.log('hello submit')
    console.log(this.movies)
  }
}

If someone have ideas, I will be happy!


Solution

  • It is because you are making a asynchronous call using the http client, which means by the time your are running

    console.log(this.movies)
    

    your movies may not be loaded. You can move your console.log inside the subscribe section to see the results.

       this.searchService
          .searchMovie(movieSearch)
          .subscribe((res) => {
               this.movies = res;
               console.log(this.movies);
           });