Exploring observables for querying the OMDB API and obtaining information on movies

Hey everyone, I'm currently working on implementing a live search feature using Observables in Angular2 to fetch Movie data from the OMDB API. While I can see that it is functioning correctly in the Chrome Network tab, the results aren't showing up in the user interface.

@Component({
  selector: 'movie-card',
  templateUrl: './card.component.html'
})
export class Component implements OnInit{
  movies: Observable<Array<Movie>>;
  search = new FormControl;

  constructor(private service: MovieService) {}

  ngOnInit(){
    this.movies = this.search.valueChanges
      .debounceTime(400)
      .distinctUntilChanged()
      .switchMap(search => this.service.get(search))
  }
}

MovieService

@Injectable()
export class MovieService {
  constructor (private http: Http) { }
  get(path: string){
    return this.http
      .get('www.omdbapi.com/?s=' + path)
      .map((res) => res.json())
  }
}

In my HTML Component, I have an input field and the UI section to display the results.

<input [formControl]="search"> 

<div *ngFor="let movie of movies | async">

<h1>{{movie.title}}</h1>

Even though I can see the results in the Network Tab while typing:

The UI doesn't update with the results. Any assistance would be greatly appreciated. Thank you!

Answer №1

The API you are utilizing provides a JSON object instead of an array. For instance, when you access

http://www.omdbapi.com/?s=jason%20bourne
, the response will look something like this:

{
  "Search": [
    {
      "Title": "Jason Bourne",
      "Year": "2016",
      "imdbID": "tt4196776",
      "Type": "movie",
      "Poster": "https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BMTU1ODg2OTU1MV5BMl5BanBnXkFtZTgwMzA5OTg2ODE@._V1_SX300.jpg"
    },
    ...
  ],
  "totalResults": "16",
  "Response": "True"
}

If your service is expected to return an array of movies, it should extract the Search property from the result:

@Injectable()
export class MovieService {
  constructor (private http: Http) { }
  get(path: string){
    return this.http
      .get('www.omdbapi.com/?s=' + path)
      .map((res) => res.json().Search || [])
  }
}

Answer №2

This method proved effective for me when working with Angular 6

Service file:

import { Injectable } from '@angular/core';
import 'rxjs/RX';
import 'rxjs/add/operator/map';
import {Http, Response} from '@angular/http';

@Injectable()

 export class omdbService {
 searchMovieByTitle(title: String) {
 const url = 'http://www.omdbapi.com/?s=' + title + '&apikey=da53126b';
  return this.http.get(url).map( (response: Response ) => {
   return response.json();  } ); }

   constructor (private http: Http) { }
   }

HTML file:

     <label>movietitle</label>
      <input #input class="form-control" />
       <button mdbBtn type="button" color="info" outline="true" mdbWavesEffect
           (click)="searchMovie(input.value)" >
         Search
        </button>

     <ul class="list-group">
       <li  class="list-group-item" *ngFor =" let movie of result.Search" >
           {{movie.Title}}   {{movie.imdbID}}
      </li>
    </ul>

Ts file:

import { omdbService } from './../service/omdb.service';
import { Component } from '@angular/core';
 @Component({
             selector: 'app-search',
             templateUrl: './search.component.html',
             styleUrls: ['./search.component.scss']
                })

    export class SearchComponent  {

         title  = '';
         result: Object = null;

     searchMovie(title: String) {
        this.OmdbService.searchMovieByTitle(title).subscribe( (result) => {
      this.result = result;     console.log(result);
             });                }

      constructor(private OmdbService: omdbService) { }

        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Limiting the use of the Tab key within a modal dialog box

Currently, I have implemented a modal window that appears when a .btn link is clicked. However, I am facing an issue where users can still navigate through links and buttons in the background by pressing the Tab key. This becomes problematic especially fo ...

The type definition file for '@types' is not present in Ionic's code base

After updating my Ionic 6 project to use Angular 3, everything works perfectly in debug mode. However, when I attempt to compile for production using 'ionic build --prod' or 'ionic cordova build android --prod', I encounter the followin ...

What steps should I follow to properly set up my tsconfig.json in order to ensure that only the essential files are included when executing npm run build

Introduction I am seeking guidance on how to correctly set up my tsconfig.json file to ensure only the necessary files are included when running npm run build for my projects. I want to avoid any unnecessary files being imported. Query What steps should ...

The text inside the Mapbox GL popup cannot be highlighted or copied

I'm encountering an issue where the text in my popups is unselectable. Even though I can close the popups through various methods, such as clicking on them, the pointer remains as a hand icon when hovering over the text and doesn't change to the ...

Experiencing a problem with Typescript validation while integrating Storybook with Material-UI (

Encountering a Typescript validation issue while attempting to pass args as children to a Material-UI button in Storybook :-/ Any suggestions on how to resolve this and avoid the Typescript error? I suspect it is caused by not passing a ReactNode. Thanks ...

The expression has been altered following verification. It previously read as 'model: 1777' but now states 'model: 2222'

I've been working on this HTML code that utilizes [(ngModel)] to update input values, and I want the Total, Subtotal, and Amount Paid fields to be automatically calculated when a change is made. However, I'm encountering some issues with this app ...

Display a React functional component

Greetings, friends! I recently created a React app using functional components and now I am looking to print a specific page within the app. Each page is its own functional component, so I was wondering if it's possible to print a component individual ...

What's the best way to make a toast notification appear when an API call is either successful or encounters

Seeking guidance on incorporating toast messages within an Angular + Ionic 6 application... My goal is to display a toast message in response to events such as clearing a cart or submitting an order, with the message originating from an API call. While a ...

I am attempting to make the fade in and out effect function properly in my slideshow

I've encountered an issue where the fading effect only occurs when the page initially loads and solely on the first image. Subsequently, the fading effect does not work on any other images displayed. This is the CSS code I have implemented by adding ...

Angular 2 is throwing an error stating that the argument 'ElementRef' cannot be assigned to the parameter 'ViewContainerRef'

I'm developing an Angular 2 application with angular-cli, but when I include the following constructor, I encounter the following error: Error Argument of type 'ElementRef' is not assignable to parameter of type 'ViewContainerRef&apos ...

Ways to implement a package designed for non-framework usage in Vue

Alert This may not be the appropriate place to pose such inquiries, but I am in need of some guidance. It's more about seeking direction rather than a definitive answer as this question seems quite open-ended. Overview I've created a package th ...

Encountering an ExpressionChangedAfterItHasBeenCheckedError in Angular 6 when selecting an option from a dropdown menu

How can we fix the error mentioned below through code changes? Situation An input dropdown UI is safeguarded against unintentional value changes by a modal. However, triggering an event (such as click or focus) on the dropdown leads to the ExpressionChan ...

How come the index variable doesn't show the index in *ngFor loop in Angular 2?

When working with ng-repeat in Angular 1 to display the index, this code is used: <div ng-repeat="car in cars"> <ul> <li>Index: {{$index+1}}</li> <li>Car Name:{{car.name}}</li> </ul> </div> However, w ...

Unable to utilize Google Storage within a TypeScript environment

I'm encountering an issue while attempting to integrate the Google Storage node.js module into my Firebase Cloud functions using TypeScript. //myfile.ts import { Storage } from '@google-cloud/storage'; const storageInstance = new Storage({ ...

When Typescript calls the toString method on a Function, it produces unexpected characters like "path_1, (0, promises.writeFile)"

I'm currently attempting to convert a function into a string for transmission to a worker thread for execution. However, when imported code is included, the resulting string contains strange characters. import { HttpStatus } from '@nestjs/common& ...

A simple way to automatically fill an input field with a mask when clicking in Angular 2

When a user clicks on this span, the following action is triggered: <span data-content="15" #Fast15 (click)="enterFastTime(Fast15)" class="quick-time">15mins</span> Users can also manually input a date in the following input field. If they ...

Using ngFor to iterate over an array after it has been loaded

Currently, I am attempting to generate a list of cards after loading an array. Take a look at my code snippet: locations; constructor( private toolbarTitle: ToolbarTitleService, public popoverController: PopoverController, private syncServi ...

Could someone provide an explanation for the meaning of the phrase "class User extends Model<UserAttribute UserCreationAttribute>"?

View Image of the Issue I am puzzled by why we are utilizing both UserCreationAttribute and UserAttribute in that specific arrow, especially when UserCreationAttribute is created by omitting one field from UserAttribute. Can someone please clarify this fo ...

Updating an array in a single line of code in Javascript can be achieved

Can the code below be optimized? const item: any; // New data const index: number = basketModel.data.coupons.findIndex( (x: any) => x.couponId === item.couponId ); if (index === -1) { // If new item, push it to array ...

What is the best way to time a Google Cloud Function to execute at the exact second?

In my attempt to schedule a cloud function using the Pub/Sub trigger method along with crontabs, I realized that it only provides granularity to the nearest minute. However, for my specific application - which involves working with trades at precise time ...