Having trouble iterating through an array of objects in Angular6

I'm having trouble fetching movie data from omdbapi and displaying it in HTML

.ts

import { Component, } from '@angular/core';    
import { HttpClient } from '@angular/common/http';    

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private _httpClient: HttpClient) {}
  results: any = [];
  
  getMovies(title) {
    `enter code here`
    this._httpClient.get("http://www.omdbapi.com/?apikey=d5dc2a5a&s=" + title)
      .subscribe((data) => {
        this.results = data;
        //this.results.Search;
        console.log(this.results)
      })
  }
}

Console output

Answer №1

It seems like you're experiencing an issue with the *ngFor directive in your Angular template, specifically with the results variable. The problem arises because you are assigning an Object to results instead of an iterable data structure.

Upon examining your screenshot, it appears that there is a Search array within your data.

To resolve this issue, modify the line from this.results = data; to this.results = data.Search;

import { Component } from '@angular/core';    
import { HttpClient } from '@angular/common/http';    

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private _httpClient: HttpClient) {}

  results: any = [];

  getMovies(title) {
    this._httpClient.get("https://www.omdbapi.com/?apikey=157f9eb7&s=" + title)
      .subscribe((data: any) => {
        this.results = data.Search;
        console.log(this.results);
      })
  }

  ngOnInit() {
    this.getMovies('The Dark Knight');
  }

}

For further clarification and demonstration, check out this Sample StackBlitz link.

Answer №2

To accomplish this task, you can utilize the keyvalue pipe in the following manner:

<div *ngFor="let entry of data | keyvalue">
   <b>{{entry.key}}</b> : <b>{{entry.value}}</b>
</div>

Answer №3

If your response is an object, remember to use the ? operator in your *ngFor loop to access an array when working with asynchronous HTTP services.

<ul>
   <li *ngFor="let result of results?.Search">{{result.Title }}</li>
</ul>

To display the total number of results, you can do this:

<span>Total: {{results?.totalResults}}</span>

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

Make sure to send individual requests in Angular instead of sending them all at once

I am looking to adjust this function so that it sends these two file ids in separate requests: return this.upload(myForm).pipe( take(1), switchMap(res => { body.user.profilePic = res.data.profilePic; body.user.coverPic = res.data.coverPic; ...

Implementing validation logic on button click using TypeScript

I'm struggling to get my validation to work for empty fields using the method below. Can anyone provide some guidance or suggestions? Thanks. Here is my template: <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" class="nobottommargin ad ...

What could be causing these Typescript compilation errors I am experiencing?

I am puzzled by the appearance of these errors, especially since I copied the entire ClientApp folder from a running application where they did not exist. https://i.sstatic.net/tcO5S.png Here is the structure of my project: https://i.sstatic.net/P4Ntm.p ...

Creating a unique pattern using JavaScript code

I have an HTML input field set up like this: <div class="form-group"> <div class="col-sm-6"> <label for="inputCalculator" class="control-label">Calculation:</label> <input class="form-control" type="text" ...

"Implementing Ionic 2 tabs allows for retrieving the previously selected option with the

Here is the code I am currently working on: onTabsChange(abc) { let selected_tab = this.tabs.getSelected(); let tab_index = selected_tab.index; console.log(tab_index); // should print current tab index but it prints previously selected tab index ...

manipulate and organize document containing text

I received a text file for a project task that requires me to calculate the total points for each team and display the top 5 teams. Here is a snippet of the text file content: FRAMae Berenice MEITE 455.455<br> CHNKexin ZHANG ...

"What is the best way to prevent a button from being enabled in Angular if a list or array is not

I am incorporating data from my service in the component: ngOnInit() { this._sharedService. getReceiptItem().takeUntil(this.ngUnsubscribe). subscribe(products => this.receiptItems = products); } Is there a way to deactivate a button if there ...

Issues with data texture rendering in the most recent iteration of the third version

I am experiencing a problem with my code that renders a static bitmap in three js. It was working fine in version 110 but stopped working in version 147. I have checked the changelog to see if there were any differences but couldn't find anything. Th ...

Angular 5 async-await issue causing unexpected behavior

I am encountering an issue with making a "synchronous" http call in Angular 5. After examining the code below: console.log("1) Before async-await call"); this.setJwtToken(); console.log("3) After async-await call"); and async setJwtToken(): Promise<a ...

Creating an object key using a passed literal argument in TypeScript

Can the following scenario be achieved? Given an argument, how can we identify the object key and access it? Any potential solutions? async function checkKey(arg:'key1'|'key2'){ // fetchResult returns an object with either {key1:&apo ...

Creating sparse fieldset URL query parameters using JavaScript

Is there a way to send type-related parameters in a sparse fieldset format? I need help constructing the URL below: const page = { limit: 0, offset:10, type: { name: 's', age:'n' } } I attempted to convert the above ...

The FaceBook SDK in React Native is providing an incorrect signature when trying to retrieve a token for iOS

After successfully implementing the latest Facebook SDK react-native-fbsdk-next for Android, I am facing issues with its functionality on IOS. I have managed to obtain a token, but when attempting to use it to fetch pages, I keep getting a "wrong signature ...

The clash between angulartics2 and rxjs causing a dependency issue

My package.json currently lists the following dependencies: "dependencies": { "@angular/animations": "~12.1.0", "@angular/common": "~12.1.0", "@angular/compiler": "~12.1.0", "@a ...

Unlocking the potential of the search pipe in Angular 6

Check out this Data Model: items1 = [ title: 'Abc', items_containers : [ title: 'edf', items_containers: [ title: 'pqr', items_container: [ ............ ...

Best approach for removing elements from numpy arrays

Seeking a more efficient solution for this algorithm. The goal is to remove all data points from 3 arrays if the radius value exceeds a user-defined maximum. This code iterates through the 'rad_vec' array, removing elements from three numpy arra ...

Trouble with Playwright test loading local URL

I'm encountering difficulties with the homepage loading in my application, despite having what I believe to be correct configurations. The test and playwright config are as follows: example.spec.ts import { test, expect, chromium } from '@playwr ...

Patterns for Spring Boot backend and Angular frontend designor Strategies for designing a Spring

I have developed an application that utilizes Spring Boot for its back end and Angular for the front end, connected through APIs. The Spring Boot components include: Dao Controller Entity Service and other classes. Upon studying further, it appears that ...

Switch out every second instance of a specific character within a given string

I have been on a quest to find a solution for this issue, but my search has been in vain. My suspicion is that I may not even be looking in the right places. Initially, I start with a string which I later convert into an array. The string is structured li ...

"I am looking for a way to receive a response from a loopback in Angular7

Currently, I am utilizing angular7 with loopback. While I can successfully retrieve data, I am unsure how to receive error messages and response statuses. It would be helpful for me to understand what my response code is at the time of the request. Output ...

Leveraging gulp to enhance the module namespace in the TypeScript output of various files

I faced an issue when using the methodology of one file - one class in a TypeScript project, as shown in the example below. File Greeter.ts module App { export class Greeter { constructor(public greeting: string) { } public greet() { ...