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

Exploring the process of linking a C# REST API to an Ionic 2 mobile application

I am completely lost on how to connect an asp.net web api with my ionic 2 mobile app. Any help or advice on resolving this problem would be greatly valued! ...

Enhancing JSON data: Transforming basic JSON structure into more complex format

I am currently working on a typescript file that is receiving a JSON response from an external API. I am in need of assistance to convert the received JSON into a different format. Could someone please help me with this JSON conversion task? Sample JSON d ...

Obtain a filtering dropdown list directly from the database within Ag-grid

Currently in my interface, I am attempting to implement a filter for the FOLDER column. This filter is supposed to retrieve data from the database and present it in a dropdown checkbox within that column. The filtering should be based on the selected data. ...

Generating a composer method in TypeScript (Flow $Composer)

While flow supports $Compose functions, the equivalent mechanism seems to be missing in TypeScript. The closest thing I could find in TypeScript is something like https://github.com/reactjs/redux/blob/master/index.d.ts#L416-L460. Is there a native equivale ...

Issue with implementing MUI Style Tag in conjunction with styled-components and Typescript

I have created a custom SelectType component using Styled Components, which looks like this: import Select from '@mui/material/Select'; export const SelectType = styled(Select)` width:100%; border:2px solid #eaeaef; border-radius:8px ...

What is the significance of the IRenderFunction interface definition in FluentUI?

Recently diving into TypeScript, I've begun working with DetailsList in Fluent UI. Check it out here: https://developer.microsoft.com/en-us/fluentui#/controls/web/detailslist. I'm exploring the onRenderRow property, which is of type IRenderFunct ...

Setting the selected <ion-option> in Ionic 3

Is it possible to programmatically set a default selected option in a dynamically created select menu using Ionic 3 and Angular? I want to make sure "Select State" is automatically chosen if the user hasn't made a selection yet, but I'm having t ...

Exploring Objects within an Array in Ionic 2 and AngularJS 2

I am currently working on displaying reviews obtained from a Laravel API, showcasing feedback on various meals. The goal is to create a slideshow of review messages along with additional data as presented in the array of Objects below: { "2": { ...

Testing onClick using Jest when it is not a callback function in props

I have discovered various ways to utilize mock functions in jest for spying on callback functions passed down to a component, but I have not found any information on testing a simple onClick function defined within the same component. Here is an example f ...

A guide on renewing authentication tokens in the Nestjs framework

import { ExtractJwt, Strategy } from 'passport-jwt'; import { AuthService } from './auth.service'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable, UnauthorizedException } from '@nestjs/common&apo ...

Adjust text size based on device orientation changes

I'm struggling to dynamically change the font size based on screen orientation and width. How can I adjust the font size when switching between landscape and portrait mode? I attempted using an event listener, but it's not updating the font size. ...

Exploring Typescript's null chain and narrowing down types

Recently, I encountered a situation where typescript seems to be incorrectly narrowing the given type. (value: number[] | null) => { if ((value?.length ?? 0) > 0) value[0]; }; Even though the condition will not be true if the value is null, in th ...

Reversing ngModel modifications does not accurately display changes in the view

Presently, my table contains editable cells, with the functionality to undo changes to each cell. To achieve this, I initially created a duplicate of each object in the array. Upon initialization, I mapped the array to create a new array with old values s ...

I am looking for guidance on removing the bottom line from the ionic 4 segment indicator. Any advice or tips on

.segment-button-indicator { -ms-flex-item-align: end; align-self: flex-end; width: 100%; height: 2px; background-color: var(--indicator-color); opacity: 1; } I am a beginner in hybrid app development and ...

Angular2 RxJS stream initiates an individual HTTP call for every child in the parent collection

I am currently working on a component that fetches a collection of objects (users) using http. After getting the list of users, I need to make individual http calls to fetch additional details of each user. I am looking for guidance on how to achieve this ...

The function column.getHeaderGroupProps does not seem to be available

Struggling with the initial setup of react-table with typescript. I keep encountering an error related to the data passed into my table function: column.getHeaderGroupProps is not a function TypeError: column.getHeaderGroupProps is not a function at ht ...

Tips for finding the displayRows paragraph within the MUI table pagination, nestled between the preceding and succeeding page buttons

Incorporating a Material-UI table pagination component into my React application, I am striving to position the text that indicates the current range of rows between the two action buttons (previous and next). <TablePagination ...

Angular: Merge two Observables to create a single list and fetch the combined data

I am currently working on creating a function that returns an observable with a list, compiled from several observables. I feel like I am very close to finding the solution because the debugger stops right before displaying the list. Here is my code: ts t ...

Exciting new venture utilizing Angular version 15 in combination with the latest Firebase 9

Recently, I set up node version 18.10.0 and attempted to start a fresh Angular 15 project using Firebase 9 for hosting, Firestore database, and authentication. However, after running the commands below, I noticed that the @angular/fire directory was missin ...

The operation of assigning the value to the property 'baseUrl' of an undefined object cannot be executed

I recently created a JavaScript client using NSWAG from an ASP .NET Rest API. However, I am encountering some errors when attempting to call an API method. The specific error message I am receiving is: TypeError: Cannot set property 'baseUrl' of ...