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:

https://i.sstatic.net/Zwwle.png

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

What steps should I take to retrieve my information from a typescript callback function?

While I am familiar with using callbacks in JavaScript, I have recently started learning Angular and TypeScript. I am facing an issue with getting my data from a service back to where I need it after executing the callback function. The callback itself i ...

Can you identify the nature of the argument(s) used in a styled-component?

Utilizing typescript and react in this scenario. Fetching my variable const style = 'display: inline-block;' Constructing a simple component export const GitHubIcon = () => <i className="fa-brands fa-github"></i> Enh ...

Utilizing indexes to incorporate elements into an object array

I'm currently working on a project using Angular. I have an index coming from the HTML, and here is the code snippet: save(index){ //this method will be called on click of save button } In my component, I have an array structured like this: data = [{ ...

Changing a numeric string into a number within an Angular 2 application

Looking for advice on comparing Angular 2 expressions. I have an array of data stored as numeric strings in my database and I need to convert them to numbers before applying a condition with ngClass for styling purposes. Any suggestions on how to perform ...

Unable to access the HTTP POST response data beyond the .subscribe method

I am facing an issue with accessing data from a variable set after making an HTTP request to a server. The request returns the correct data as a response, but I am unable to access the variable data from another method. Below is my code snippet: public u ...

Tips for preventing the error message "The property 'map' is not present on type 'string | string[]'."

I received an error message stating Property 'map' does not exist on type 'string | string[]': const data = [ ['1', ['11']], ['2', ['21']], ['3', ['31']], ] data.map(top ...

Has anyone tried using the JSON1 extension with Angular in an Ionic project?

Looking to extract SQlite information in JSON layout utilizing the JSON1 extension. Yet, upon trying to execute the code, an error message appears. Error {"message":"sqlite3_prepare_v2 failure: no such function: json_object", "co ...

Text input builder design pattern akin to roster creator design pattern

I have a need to create a custom free form text box builder that functions similarly to the listbuilder demonstrated in the attached image. The goal is for users to be able to input values into the textbox on the front-end HTML, click an Add button, and h ...

Include a link in the email body without displaying the URL

My concern revolves around displaying a shortened text instead of the full link within an email. When the recipient clicks on "Open Link," they should be redirected to the URL specified. The text "Open Link" must appear in bold. My current development fram ...

Different and Basic Designs for mat-table

Is there a way to customize the appearance of the material data table (mat-table) beyond the pre-built themes? I'm specifically interested in styles like table-striped, table-sm, or table-bordered from bootstrap 4. Is it possible to apply these style ...

Is there a way to retrieve a specific type from a union-based type by using a generic function in Typescript?

When working with my API, I have noticed a consistent pattern where it returns either a specific type or a TypeScript type called BadResult, as shown below: type Result1 = CreatedPersonResult | BadResult; type Result2 = CreatedRoleResult | BadResult; To s ...

Converting a string to an HTML object in Angular using Typescript and assigning it to a variable

I am facing an issue with passing HTML content from a service to a div element. I have a function that fetches HTML content as a string from a file and converts it into an HTML object, which I can see working in the console. However, when trying to assign ...

What is the reason for an optional object property being assigned the 'never' type?

I'm having trouble understanding the code snippet below: interface Example { first?: number, second?: { num: number } } const example: Example = { first: 1, second: { num: 2 } } function retrieveValue<Object, Key exte ...

Issues with Angular 2 and Deserialization of .NET List<T>

I'm encountering issues when trying to deserialize a .NET List into an Angular 2 array. An error keeps popping up: ERROR Error: Cannot find a differ supporting object...NgFor only supports binding to Iterables such as Arrays. I've looked around ...

Loop through a collection of map instances in TypeScript

In my TypeScript code, I am making a call to an API method in a Java class that returns a list of maps. The TypeScript file includes the code snippet below. When attempting to retrieve data from dataBody, it displays as [Object Object]. I need assistance ...

Here is a unique version: "Dealing with Node.js ES6 (ESM) Modules in TypeScript can be tricky, especially when the TypeScript Compiler (TSC) fails to emit the

I am facing an issue while transpiling my TypeScript project to JavaScript. I have set the project to resolve as an ES6 Module (ESM) by using the "module":"ES6" configuration, but the problem persists. This is the current setup in my ...

Using ngFor to dynamically populate drop-down options from a key value object in Angular 2

How can I use ngFor in Angular 2 to dynamically populate options in dropdown menus from a key value object? Below is the JSON data: { "employment": { "0": "Employed", "2": "Un-employed", "3": "Retired", "4": "Self" "V ...

Using a basic XML file in Angular: A beginner's guide

Incorporating XML into my Angular app is a necessity. While the most straightforward approach would be to store it as a string, like so: xml = '<?xml version="1.0" encoding="UTF-8"?>\n' + '<note>\n ...

Transforming a JavaScript Date object to a Java LocalDateTime

In my current project, I am facing a challenge while attempting to pass UTC time from a JavaScript front end to a Java backend. My initial approach involved utilizing the Date.toISOString() method and sending the generated object to the Java backend. Howev ...

Designing the Pull to Refresh feature in Nativescript Angular

I've been experimenting with the Nativescript Angular Pull to Refresh Styling demo (Link) and I'm running into an issue where this.myListViewComponent remains undefined, causing the following snippet not to trigger: if (this.myListViewComponent ...