Issue: Unable to locate a matching object '[object Object]' of type 'object'. NgFor can solely bind to data structures like Arrays and Iterables

I am facing an error that says "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." I am trying to create a Notification list but I can't figure out what mistake I have made.

HTML

<ng-container *ngIf="notificationModal">
      <div class="side-panel__notif-container">
        <div class="side-panel__notify-header">
        <span class="side-panel__usr-profile-close" (click)="clkNotifcationPnl()">
          <fa-icon [icon]="faClose"></fa-icon>
        </span>
        <span class="side-panel__usr-noti-hdr">Notifications</span><br>
      </div>
      <div class="side-panel__notify-body">
        <div class="side-panel__user-notif-cont">
          <div class="drop-content">
         <ul class="mt-2 list-group notify-contents">
          <li *ngFor="let items of notify">
            <div class="col-md-3 col-sm-3 col-xs-3">
              <div class="notify-img">
                <span [ngStyle]="{'background-image': loadProfilePic()}" class="side-panel__user-notif-img fa"></span>
              </div>
            </div>
            <div class="col-md-9 col-sm-9 col-xs-9 pd-l0">{{items.notifyFromName}}
             <p>{{items.notifyMessage}}</p> 
            <p class="time">{{items.notifyDate}}</p>
            </div>
          </li>

        </ul>
        </div>

        </div>
      </div>
      </div>
    </ng-container>

Component

public onClickUserNotif() {
   this.headerService.isLoading = true;
    return this.commonService.getNotificationList().subscribe((res) => {
      if (res['status'].code === 0) {
        this.headerService.isLoading = false;
        let notify = res['notification']
        if(notify.length > 0) {
          this.notificationModal = true;

          console.log(notify);


        }

      }
    });

  }

And this value is displayed when I console.log(notify)

https://i.stack.imgur.com/M9m0h.png

Answer №1

let notify = res['notification']

This code creates block level scope, which means the local scope will not reflect this value. Angular binds to local scope, not block level scope. Therefore, you need to bind a local variable outside of that function.

class ComponentName {
    notify: any[];
    // ...
   onClickUserNotif() {
       // ...
       this.notify = res['notification'];
   }
}

Edit:

Here are some key points:

  • Before my suggestion, there was no locally scoped notify.
  • Angular does not throw an error on a null value.
  • Creating the locally scoped notify did not resolve the issue.

Therefore, the only possible solutions or issues I see are:

  • You might be looking at HTML that does not correspond to the .ts file you are working with, or
  • The res['notification'] is being altered in your commonService and the notify variable is reflecting those changes.

Sidenote:

  • In your ngOnInit function, you are subscribing to the same service as in your other function. It seems unnecessary to resubscribe.
  • Although you use takeWhile() to manage active subscriptions, it only affects the outer subscription, not the inner one.

Answer №2

It is highly recommended to err on the side of caution and ensure that you always maintain this array:

class ComponentName {
    notify: any[] = []; // initializing an empty array
    // ...
   onClickUserNotif() {
       // ...
       this.notify = res['notification'];
   }
}

// When referencing the properties in the template, use the ? to handle potential absence of properties: 
            <div class="col-md-9 col-sm-9 col-xs-9 pd-l0">{{items?.notifyFromName}}
             <p>{{items?.notifyMessage}}</p> 
            <p class="time">{{items?.notifyDate}}</p>
            </div>

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

Greetings, I am currently using Angular version 3n 2 rc5 and I am hoping to execute a function called "change" that will perform two separate functions

I am working on a piece of code where I need to assign a value to a variable and then trigger a function simultaneously. I have attempted the following approach, but I am not sure if it is correct. Can someone provide some assistance? view.html <input ...

When a property is removed from a variable in an Angular Component, it can impact another variable

During the iteration of the results property, I am assigning its value to another property called moreResults. After this assignment, I proceed to remove array elements from the testDetails within the moreResults property. However, it seems that the remova ...

The z-index overlapping problem in webkit browsers is a result of Angular 7 animations

I have implemented staggered animations in my Angular 7 application to bring elements to life upon page load. However, I am facing a strange z-index problem with one of my components. Here is the animation code: @Component({ selector: 'track-page& ...

«IntelliJ: Effortless Live Reload with Spring Boot and Angular»

For my software development projects, I often work with a spring boot maven project alongside an Angular 5 project. To optimize the workflow, I usually start by building the "dist" folder using the npm run build:prod command and then incorporating it into ...

The specified 'IArguments' type does not qualify as an array type

Currently working on crafting a personalized logger. It's a fairly straightforward process, but I'm running into some errors that are muddying up my output. Here's what I have so far: @Injectable() export class Logger { log(...args: any ...

No search results found for Mongoose text search query

Despite using Mongoose 5.7.8 for my app, the text search feature is not yielding any results. Below is a schema/model example: import mongoose, { Document, Schema } from 'mongoose'; import { Moment } from 'moment'; import { IUser } fr ...

Encountering a "No such file" error when attempting to execute an Angular application as a

The Angular project's main folder houses the Dockerfile, along with package.json and other files. The Dockerfile structure is as shown below: FROM node:lts-alpine AS builder WORKDIR /app COPY . . RUN npm install RUN npm run build FROM nginx:alpine COP ...

Misunderstanding the concept of always being right

Here is a code snippet that raises an error in TypeScript: class Status { constructor(public content: string){} } class Visitor { private status: Status | undefined = undefined; visit(tree: Tree) { if (tree.value > 7) { this.status = new ...

Ensuring User Authentication in Angular with Firebase: How to Dynamically Hide the Login Link in Navigation Based on User's Login Status

After successfully implementing Angular Firebase email and password registration and login, the next step is to check the user's state in the navigation template. If the user is logged in, I want to hide the login button and register button. I tried s ...

The functionality of ZoneAwarePromise has been modified within the Meteor framework

After updating to the latest Angular 2.0.1 release on Meteor 1.4.1.1, I'm facing an error that says: Zone.js has detected that ZoneAwarePromise (window|global).Promise has been overwritten I've attempted running meteor update and meteor reset, b ...

How can I call a global function in Angular 8?

Currently implementing Angular 8, my objective is to utilize downloaded SVG icons through a .js library. To achieve this, I have made the necessary additions to my .angular.json file: "scripts": [ "node_modules/csspatternlibrary3/js/site ...

Using angular 7 to apply a dynamic CSS class on a span element

I want to dynamically change the CSS class of a span element in an ngx datatable based on the value. Here is my HTML code: <ngx-datatable #orderinvoice class="bootstrap" [rows]="invoiceSource" [headerHeight]="50" [footerHeight]="50" [rowHe ...

What is the correct approach for detecting object collisions in Phaser 3?

Hey everyone, I'm facing a problem and could use some assistance. Currently, I am trying to detect when two containers collide in my project. However, the issue is that the collision is being detected before the objects even start moving on screen. It ...

Unveiling the magic behind using jasmine to spy on a generic

I am trying to spy on a generic method in TypeScript, but Jasmine is not recognizing it. Here is the code snippet: http: HttpClient <- Not actual code, just showing type. ... this.http.get<Customer[]>(url); In this code, I am trying to mock the ...

Utilizing the dialogue feature within Angular 6

Situation: I am managing two sets of data in JSON format named customers and workers: customers: [ { "cusId": "01", "customerName": "Customer One", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...

The form doesn't seem to be functioning properly when I incorporate the formgroup and service within the ngOnInit() method

I implemented the formgroup code in ngOnInit() and also utilized a service in ngOnInit(). However, the asynchronous nature of the form is causing issues. The full code on StackBlitz works when I use dummy JSON data within the constructor. Check out the wor ...

Measuring the height of an element within its parent component using Angular 4

Check out my demo here I've created a basic parent component along with a child component. Is there a way to retrieve the height of the parent div from within the child component? import { Component, Input, ElementRef, OnInit, ViewChild } from &apo ...

Is it possible to modify the CSS styling in React using the following demonstration?

I am attempting to create an interactive feature where a ball moves to the location where the mouse is clicked. Although the X and Y coordinates are being logged successfully, the ball itself is not moving. Can anyone help me identify what I might be overl ...

Is it possible to categorize a JSON object based on its properties and then count the occurrences of each property within

I have an array of objects containing booking information and I need to calculate the count of each booking item in every object. const arr = [ { "ID" : 1, "Name":"ABC", "Bookings":[ { & ...

How to upload files from various input fields using Angular 7

Currently, I am working with Angular 7 and typescript and have a question regarding file uploads from multiple input fields in HTML. Here is an example of what I am trying to achieve: <input type="file" (change)="handleFileInput($event.target.files)"&g ...