-1

I've been learning Angular (6) the last couple days, and I've been trying to make a request to the omdb api. Here's the code, retrieve a random movie id and looking for that specific one. But I can't reach the api or the function, I have a couple components, the buttons and the container for the movies.

import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-options',
  templateUrl: './options.component.html',
  styleUrls: ['./options.component.css']
})
export class OptionsComponent implements OnInit {
  omdbData = ['0386676', '1865718', '0098904', '4508902', '0460649', '2861424', '0108778', '1305826', '0096697', '0149460'];
  randomItem = this.omdbData[Math.floor(Math.random() * this.omdbData.length - 1) + 1];
  result: Object;
   constructor(private http: Http) {
   // console.log(this.randomItem);
   // this.searchData();
  }
  id = this.randomItem;
  searchData() {
    this.http.get('https://cors-anywhere.herokuapp.com/http://www.omdbapi.com/?i=tt' + this.id + '&apikey=')
    .pipe(map(
      (res: Response) => {
        const result = res.json();
        console.log(result);
      }
    ));
    }
  ngOnInit() {
    this.searchData();
  }

}
Karma00
  • 9
  • 4
  • Your code snippet gives an error when running it. Second you must subscribe to your observable to actually make a call to the api – MikNiller Feb 05 '19 at 16:00

2 Answers2

0

You need to subscribe to the observable returned by the request like so:

searchData() {
  this.http
    .get('https://cors-anywhere.herokuapp.com/http://www.omdbapi.com/? i=tt' + this.id + '&apikey=')
    .pipe(map((res: Response) => res.json()))
    .subscribe(data => {
      console.log(data);
    });
}
Leo
  • 741
  • 6
  • 14
0

observables are lazy loaded in angualr so you have to subscribe them to make request to your backend APIs

searchData() {
    this.http.get('https://cors-anywhere.herokuapp.com/http://www.omdbapi.com/?i=tt' 
                 + this.id + '&apikey=')
    .pipe(map((res: Response) => res.json()))
    .subscribe(data => {
       console.log(data);
    });
    }
Ved_Code_it
  • 704
  • 6
  • 10