D
D
danilr2019-03-23 08:04:52
Angular
danilr, 2019-03-23 08:04:52

How to make API requests in Angular 7?

I need to make a request to the API https://developers.themoviedb.org/3
I need to specify two parameters, one "api_key", the second dynamically "query" = "Matrix" (for example).
I tried to do it, but apparently I'm doing something wrong

export class AppComponent {
  title = 'FinderFilms';

  baseURL: string = "https://api.themoviedb.org/3";
  route: string = "/movie/search"
  response: any;
  
  constructor(private http: HttpClient){

  }
  search(){
    const params = new HttpParams().set('api_key', 'd6a5ac2d3d7cab11a084ca8080421b20, 'title',"Матрица");
    const options = {params: params};
    this.http.get(this.baseURL+this.route , options)
    .subscribe((response) =>{
      this.response = response;
      console.log('response: ', response);
    })
  }
}

How can I specify parameters dynamically and how should I arrange it correctly?
I'm new to Angular, so if you know the answer, I beg you to chew on the answer :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
msdosx86, 2019-03-23
@danilr

search(title: string): void {
  const params = new HttpParams()
    .set('api_key', 'd6a5ac2d3d7cab11a084ca8080421b20')
    .set('title', title);
  const url = 'https://api.themoviedb.org/3/movie/search';
  this.httpClient.get(url, { params })
    .subscribe(console.log);
}

This is a terrible, but understandable example for you. Calls to the API must be made to services, never call the `subscribe` method in methods, only once in OnInit, and then pull it with `.next`.

D
Denis, 2019-03-23
@sidni

In get requests, the parameters must/can be specified in the url parameters
https://api.themoviedb.org/3/movie/search?title=Ma...
Although, according to the code, you still have the third parameter query
In general, you need to create a service for working with api so as not to duplicate the code for collecting the request and initial data and inject this service into the component instead of httpclient

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question