Home > Software engineering >  How to pass data from a component to a service, to make a new http request?
How to pass data from a component to a service, to make a new http request?

Time:03-15

I want to pass a string value from my app.component to my service, so i can open a new URL there based on this data, but for some reason, i'm getting a "Cannot read properties of undefined (reading 'toLowerCase')" error, why is that?

on my app.component.ts i have:

import { Component } from '@angular/core';
import { searchMoviesService } from './services/buscar-todos-produtos.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  movie1: any;
  movie1Data: any;

  constructor(private searchMoviesService: searchMoviesService) {}
  
  ngOnInit() {
    this.searchMoviesService.getData().subscribe((searchProdutos: any) => {
      this.movie1 = searchProdutos.films[1];
    })
    this.searchMovie();
  }

  searchMovie() {
    this.searchMoviesService.searchMovie(this.movie1).subscribe((data) => {
      console.log(data);
      this.movie1Data = data;
    });
  }

}

and my service i have:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
// import { buscarProdutos } from '../Models/buscarProdutos';
import { map, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class searchMoviesService {
  constructor(private http: HttpClient) {}

  getData() {
    return this.http.get<any[]>('https://swapi.dev/api/planets/1/?format=json');
  }

  searchMovie(data: string) {
    console.log(data);
    return this.http.get<string[]>(data);
  }

}

CodePudding user response:

The problem is not in passing a string param to the service, that part of the code looks fine.

In this snippet:

ngOnInit() {
    this.searchMoviesService.getData().subscribe((searchProdutos: any) => {
      this.movie1 = searchProdutos.films[1];
    })
    this.searchMovie();
}

In subscribing to getData() the assigning of the value to this.movie1 is asynchronous.

In other words the program execution does not wait for the value to return from that call you make. Thus it will go on and execute this.searchMovie() while the value is not yet assigned and thus undefined.

The console is just telling you that undefined has no function toLowerCase, which (although true) is not very helpful. But when something is undefined, timing issues is one of the possibilities that should jump to mind.

One thing you could do is:

ngOnInit() {
    this.searchMoviesService.getData().subscribe((searchProdutos: any) => {
      this.movie1 = searchProdutos.films[1];
      this.searchMovie();
    })
}

But there are other solutions you can try out, once you get this concept.

  • Related