There was an issue attempting to differentiate '[object Object]'. The Angular API Get Request from .Net only allows for arrays and iterables to be used

I am currently in the learning stage and consider myself a novice, so please forgive me if this question seems silly. I am working on a Movie Database project that involves integrating movies from a live API, creating a favorite list, implementing JWT authentication, and more. I have completed most of the project, but I am facing an issue with retrieving movies from a table that sits between the movies table and the users table (favorite table with a many-to-many relationship). While everything seems to work fine in my Swagger documentation and I can retrieve movies from the favorite table, I encounter an error when using *ngFor in Angular. The error indicates that it expects an array but receives an object instead. All other GET requests work properly except for this one. Here is the code snippet along with the error:

https://i.sstatic.net/n4fap.png Although I am able to retrieve the desired information in the console, the UI displays an error

Component .ts and HTML:

//HTML

<div *ngFor="let fav of requests" class="col-xl-3 col-lg-4 col-md-6 col-sm-6 col-xs-12">
    <div class="card">
        <img src="{{fav.Poster}}" class="card-img-top">
        <div class="card-body">
            <p class="card-text"> {{fav.Title}}</p>
        </div>
    </div>
</div> 

.Ts

export class FavoriteListComponent implements OnInit {

  constructor(public service: MovieService) { }
  requests: any = [];

  ngOnInit(): void {
    this.getFav();
  }

  getFav(){
    this.service.getFavorite1().subscribe(
      res => {
      this.requests = res;
      console.log(res)
    });
  }
}

MovieService

getFavorite1(){
  return this.http.get('http://localhost:5002/api/Favorite/getUsersFavorite').pipe(map(res => res));
  }

This is the GET request in .Net 5

        [Authorize]
        [HttpGet("getUsersFavorite")]
        public async Task<IActionResult> GetUsersFavoriteMovies()
        {
            string userId = User.Claims.First(a => a.Type == "UserID").Value;
            var user = await _context.DbUsers.Where(n => n.Id == Int32.Parse(userId)).Select(movies => new FavoriteView()

            {
                ImdbId = movies.Favorites.Select(n => n.ImdbId).ToList(),
                Title = movies.Favorites.Select(n => n.Movies.Title).ToList(),
                Poster = movies.Favorites.Select(n => n.Movies.Poster).ToList()

            }).FirstOrDefaultAsync();


            return Ok(user);
        }

I have tried various approaches, and the closest I have come to a solution is by changing the .FirstOrDefaultAsync() in the .NET request to .ToListAsync(). However, when I make this change, I encounter the following issue:

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

Although this resolves the error, nothing is displayed in the UI

I realize this is a lengthy question, but I am really struggling with this and would appreciate any help. Thank you!!!

Answer №1

Follow this method, it will do the trick.

<ng-container *ngIf="requests">
  <div
    *ngFor="let fav of requests.imdbId; index as i"
    class="col-xl-3 col-lg-4 col-md-6 col-sm-6 col-xs-12"
  >
    <div class="card">
      <img [src]="requests.poster[i]" class="card-img-top" />
      <div class="card-body">
        <p class="card-text">{{ requests.title[i] }}</p>
      </div>
    </div>
  </div>
</ng-container>

See it in action here: https://stackblitz.com/edit/angular-ivy-f251ko?file=src%2Fapp%2Fapp.component.html

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

Tips for enlarging a mat-expansion-panel by pressing a button in Angular?

Currently, I have a component featuring expansion panels. When clicking on the "All" tab button, all mat-expansion-panels expand perfectly in the body below. However, my goal is to make it so that clicking on the B tab will only activate and expand the pan ...

Create an Angular library that incorporates a TypeScript dependency into the compilation process

Within my Angular lib, residing in an Nx workspace... The lib relies on another local lib for shared TypeScript code. The path to the shared lib is set in the tsconfig paths configuration: "paths": { "@myOrg/sharedLib": ["lib ...

Combining information from various cells in a table into a single cell

I am working on loading a table from a database and my goal is to combine data in each column into separate cells. Below is the structure of the table: Column A Column B Column C Column D Cell a1 Cell b1 Cell c1 Cell d1 NULL Cell b2 Cell c2 NULL ...

Error in Typescript syntax within a CommonJS/Node module: Unexpected colon token found in function parameter

After validating the file with TS, there are no more errors. However, during runtime, I encounter an "Unexpected token ':'" error on any of the specified TS, such as immediately erroring on function (err: string). The following are my build and ...

What is the meaning of '=>' in typescript/javascript?

I keep coming across lots of '=>' in the code I found on the internet. Could someone please explain it to me as if I were 5 years old? (I'm searching for the specific code, and I'll share it here once I locate it).. Found it: ...

Exploring the concept of abstract method generation in TypeScript within the Visual Studio Code

Anyone familiar with a Visual Studio Code plugin that can automatically generate stub implementations for abstract methods and properties in TypeScript? I've searched through the available plugins but haven't been able to locate one. Any suggest ...

My Angular 2 observable is failing to provide my subscribers with the most up-to-date information when new data is added to

I am facing an issue with my Angular 2 observable where the subscribers are not receiving updated data, despite no build errors or console errors. The subscribers are only able to receive data during the component load in the ngOnInit section. Below is a ...

Instructions for hiding a gridview on a content page within a Visual Basic master page

Currently, I am working on adjusting the visibility of different controls on my content page depending on a combobox selection made in my master page. I have successfully passed the text of the selected item from the combobox to the content page as a par ...

Different ways to categorize elements of Timeline using typescript

I have some code that generates a timeline view of different stages and their corresponding steps based on an array of stages. Each stage includes its name, step, and status. My goal is to organize these stages by name and then display the steps grouped un ...

What is the best way to create and manage multiple collapsible Material-UI nested lists populated from an array with individual state in React

In my SideMenu, I want each list item to be able to expand and collapse independently to show nested items. However, I am facing the issue of all list items expanding and collapsing at the same time. Here is what I've attempted: const authNavigation ...

What kind of Typescript type should be assigned to setState when passed to the component?

In my setup, I have a variety of Parent components: const ParentOne = () => { const [error, setError] = useState<{ one: boolean }>({ one: false }); ...omit return ( <> <Child setErr={setError} name={"one"} /> </> ...

"Parent component is unable to modify the value of a child input field when ionViewWillEnter is

Scenario: Main page linked to subpage. Subpage accesses input data from main page. Upon navigation, main page updates variable in ionViewWillEnter. However, this change is not reflected in the subpage. Interactive Demo: https://stackblitz.com/ed ...

Generating an instance of a class by using the class name as a string

Before jumping to conclusions, please take a moment to read the following: In addition to TypeScript, my issue also involves Angular2. Main Goal I am in need of a method in app.component.ts that can take a string (Class Name) and generate an instance of ...

Is it possible for Typescript interface A to extend B while lacking certain properties from B?

My confusion lies in understanding how TypeScript interfaces function effectively. Here's what I currently have: import type { Socket, Handshake } from 'socket.io'; import type { Session } from './session'; export interface Sessio ...

Is there a way to convert a Java object into a JSON format in Java without relying on external libraries or dependencies?

public class Information { private String privilege; private String bar; private Int years; } transformed into {"privilege" : "data", "bar": "data", "years":"data"} devoid of Gson or Jackson. solely using core Java Is there a simpler approac ...

What is the process for declaring global mixins and filters on a Vue class-based TypeScript component?

Recently, I've been working on incorporating a Vue 2 plugin file into my project. The plugin in question is called global-helpers.ts. Let me share with you how I have been using it: import clone from 'lodash/clone' class GlobalHelpers { ...

Unable to locate the image file path in React.js

I'm having trouble importing images into my project. Even though I have saved them locally, they cannot be found when I try to import them. import {portfolio} from './portfolio.png' This leads to the error message: "Cannot find module &apos ...

Can ngFor be utilized within select elements in Angular?

I'm facing an interesting challenge where I need to display multiple select tags with multiple options each, resulting in a data structure that consists of an array of arrays of objects. <div class="form-group row" *ngIf="myData"> <selec ...

Executing a service prior to the loading of Angular 7 applications or components

Currently, I am in the process of developing an application using Angular 7. So far, everything is running smoothly as I have successfully managed API calls, JWT Token authentication with C#, and updating LocalStorage when needed during user login and logo ...

Is it possible to nest a component within another component in the latest iteration of Angular2?

Currently in angular2 version (V2.2.0), I am interested in utilizing a component within another component. In the past, we were able to achieve this by using the following code: import { AnotherComponent } from './another-component'; @Componen ...