An issue has occurred: Unable to locate a supporting object 'No result' of type 'string'. NgFor is only compatible with binding to Iterables like Arrays

I am attempting to utilize this code to post data from a web service.

service.ts

 public events(id: string): Observable<Events> {
    ......
    return this.http.post(Api.getUrl(Api.URLS.events), body, {
      headers: headers
    })
      .map((response: Response) => {
        let res = response.json();
        if (res.StatusCode === 0) {
          return res.StatusDescription;
               } else {
          return new Events(null);
        }
      });
  }

This code displays all my data. If the web service does not receive any data, no results are shown and this function throws an error:

ERROR Error: Cannot find a differ supporting object 'No result' of type 'string'. NgFor only supports binding to Iterables such as Arrays.

To display on the page, I used the following code:

event: Events;
  events: Events[]=[];

  getalleventsserial() {
    this.activatedRoute.params.subscribe(
      params => {
        this.ns.events(params['id']).subscribe(
          events => {
            this.event = events;
         }
        );
      }
    );
  }

html code:

<table *ngFor="let item of event">
<tr>
<td>{{item.id}}</td>
<td>{{item.alarmnr}}</td>
<td>{{item.name}}</td>
</tr>
</table>

Please, could you provide a solution for this issue? Thank you

Answer №1

If your service returns the string 'No result' when there is no data for an event, you can use the *ngIf directive to handle this condition.

To display the event only when it has data, implement the following logic:

<table *ngIf="isEmpty">
  <tr *ngFor="let item of event">
    <td>{{item.id}}</td>
    <td>{{item.alarmnr}}</td>
    <td>{{item.name}}</td>
  </tr>
</table>

Place this code in your your.component:

event: Events;
events: Events[]=[];
isEmpty: boolean;

getalleventsserial() {
  this.activatedRoute.params.subscribe(
    params => {
      this.ns.events(params['id']).subscribe(
        events => {
          this.event = events;
          this.isEmpty = (Array.isArray(this.event)) ? true : false;
        });
    });
}

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

Implementing atob in Angular's interface

Looking for a solution to a token storage issue, my initial thought is that interfaces might be the way to go. Presently, my login code looks like this: import { Component } from '@angular/core'; import { FormBuilder } from '@angular/forms&a ...

What is the best way to create a generic function parameter for a single property of an object?

I am trying to refactor a generic function into accepting parameters as a single object function test<T>(a: string, b: T, c: number) Instead, I want the function to receive an object like this: function test(params: {a: string; b: T, c: number}) I ...

Am I on track with this observation?

I am currently using the following service: getPosition(): Observable<Object> { return Observable.create(observer => { navigator.geolocation.watchPosition((pos: Position) => { observer.next(pos); observer.c ...

Angular Dropdown Menu

When working with Angular, I encountered an issue with creating a drop down. Despite having a list of items, only the first item is displayed in the drop down menu. <div class="form-group"> <h4>Projects</h4> <div *ngFor="let ...

Syncing a line's position with the cursor in Angular using the ChartJs Annotation Plugin

I've been working on creating a crosshair using the annotation plugin, and while I've been able to modify the line's value, it doesn't seem to update on the chart. Here are the details of my chart options : public financialChartOptions ...

Creating a sleek navigation bar and sliding feature within the header of your Ionic 2

I am looking to create a sliding header for my website where the gallery hides and the navbar moves to the top as I scroll down, similar to the gif provided. Any help or ideas on how to achieve this would be greatly appreciated. Thank you. https://i.sstat ...

Can a Typescript type alias be altered in real time?

Currently, I am developing an Angular library that will function as an API client. The challenge I am facing is that some of the applications utilizing this library are configured with an HttpInterceptor to automatically transform date strings into JavaScr ...

Ensuring type safety in TypeScript arrow function parameters

I have encountered an issue with my code when setting "noImplicitAny" to true. import ...; @Injectable() export class HeroService { private _cachedHeroes: Observable<Hero[]>; private _init: boolean; private _heroesObserver: Observer<Hero[ ...

Utilize Array.push to add 2 new rows to a table using Angular 4

I have two arrays that are almost identical, except for two items which are the fakeDates: this.prodotti.push({ idAgreement: this.idAgreement,landingStatus: this.landingStatus, landingType: this.landingType, startDate: this.startDate, expirationDate: thi ...

Testing in Vue revealed an unexpected absence of data

I am facing difficulties when it comes to creating tests. Currently, I have a view that is supposed to verify an email address using an authentication code. At the moment, the view exists but no connection is established with an email service or code gener ...

Cannot utilize remote.require() in TypeScript due to compatibility issues

Recently, I've been facing a frustrating issue while developing an Electron application in TypeScript. I've been trying to execute a module from a renderer process using the code snippet below: import { remote } from 'electron' const ...

Incorporating optional fields into the form builder without being mandatory

For my current project on Ionic 4, I have implemented a form builder to create and validate forms. I have also included the [disabled] attribute in the form to disable it if all fields are not valid. However, I noticed that even if I do not add Validators ...

Safari does not support RequestAnimationFrame in Angular 4

I'm currently working with material design in an Angular 4 project. However, I've encountered an issue where the project does not load properly on Safari due to an error related to RequestAnimationFrame. Does anyone know how to fix this problem? ...

Updating Firebase token in Angular when it has expired

Currently working on a website using Angular, I have integrated the Firebase SDK for email/password authentication. The main aim is to automatically generate a new token if the user closes the site and returns after a week. However, I am unsure which func ...

What is the best method to retrieve HTTP headers from the backend and simultaneously send HTTP parameters to it in ASP.NET Core and Angular?

I am currently working with Angular 15 and ASP.NET Core 5. The backend retrieves paged items based on the parameters pageSize and pageIndex. Once the action method receives the pageSize and pageIndex parameters, it sends both the paged items and the total ...

Effective Strategies for Managing Real-Time Messaging in a MEAN Stack Application

I'm looking to create a MEAN Stack application, but I'm struggling to find clear guidance on how to implement live messaging similar to applications like WhatsApp or Facebook Messenger. At first, I considered using the setTimeout function and ma ...

Allow users to upload .docx and .xlsx file types with an input field of

I'm currently working on a file upload feature that requires checking for allowed file extensions. The two file extensions allowed are .docx and .xlsx. I've noticed that when I try to log the file extension using console.log, it doesn't prin ...

What causes TypeScript to generate an error when using two array of object types, but not when using the shape of both?

There are two basic types of data available: type DataA = { percent: string; exchange: string; }; type DataB = { price: number; exchange: string; }; I'm puzzled as to why TypeScript gives errors when I try to use both types together: const ...

`Is there a way to display a server-side file (image) in Angular using rendering techniques?`

After successfully saving a file in the database using my Java server, I am now faced with the challenge of displaying that file on my Angular side. The file is of MIME type image/jpg. When attempting to send a GET request, I can retrieve the image correc ...

The typescript MenuProvider for react-native-popup-menu offers a range of IntrinsicAttributes

Looking to implement drop-down options within a Flatlist component, I've utilized the React Native Popup Menu and declared MenuProvider as the entry point in App.tsx. Encountering the following error: Error: Type '{ children: Element[]; }' ...