Issues with Angular 2 and Deserialization of .NET List<T>

I'm encountering issues when trying to deserialize a .NET List into an Angular 2 array. An error keeps popping up:

ERROR Error: Cannot find a differ supporting object...NgFor only supports binding to Iterables such as Arrays.

I've looked around but none of the suggested solutions have worked for me so far: https://github.com/angular/angular/issues/6392

C#

Model

public class Filter
{
    public string filterType { get; set; }

    public string filterKey { get; set; }

    public string filterValue { get; set; }
}

Controller Action

       public List<Filter> Filters { get; set; } = new List<Filter>()
        {
            new Filter()
            {
                filterType = "TypeA",
                filterValue = "ValueA",
                filterKey = "TypeA|ValueA"
            },
            new Filter()
            {
                filterType = "TypeB",
                filterValue = "ValueB",
                filterKey = "TypeB|ValueB"
            }
        };

    // GET api/values
    [HttpGet]
    public ActionResult Get()
    {
        var response = JsonConvert.SerializeObject(Filters);

        return new JsonResult(response);
    }

I have verified using both POSTMAN and Chrome Developer Tools that this controller is indeed returning the correct JSON:

    [{"filterType":"TypeA","filterValue":"TypeA","filterKey":"TypeA|ValueA"},
 {"filterType":"TypeB","filterValue":"ValueB","filterKey":"TypeB|ValueB"}]

Angular

Model (filter.ts)

export class Filter{
      filterType: string;
      filterKey: string;
      filterValue:string;
  }

Service (filter.service.ts)

   @Injectable()
export class FilterService {

  private apiUrl: string = "http://localhost:7639/api/filters";


  constructor(private http: Http) { }


  public getFilters = (): Observable<Filter[]> => {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
        return this.http.get(this.apiUrl,options)
                         .map(res => <Filter[]>res.json())
                         .do(x => console.log(x)) <-- This clearly logs the JSON
                         .catch(this.handleError);

  }

  private handleError(error:Response){
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }

}

Component (filter.component.ts)

export class FilterComponent implements OnInit{
      title = 'Filters';
      public filters: Filter[];

      constructor(private filterService: FilterService) {

       }

      ngOnInit() {
        this.getFilters();
      }

      private getFilters(){
        this.filterService.getFilters().subscribe(filters => {
          this.filters = filters;
          console.log(filters);
        },
        error => {
          console.log(error);
        }, () => {

        });
      }
    }

Component HTML (filter.component.html)

<h1>{{title}}</h1>

<div *ngFor="let filter of filters">
    <p>{{filter.filterType}}</p>
    <p>{{filter.filterValue}}</p>
    <p>{{filter.filterKey}}</p>
</div>

Any assistance regarding this matter would be highly appreciated

Answer №1

The solution turned out to be surprisingly straightforward.

// Fetch data from API
[HttpGet]
public ActionResult RetrieveData()
{
    var responseData = JsonConvert.SerializeObject(DataFilters);

    return new JsonResult(responseData);
}

I realized I was unnecessarily serializing the list and returning it as a string.

By making a simple adjustment to the method above, the issue was resolved:

// Fetch data from API
[HttpGet]
public ActionResult RetrieveData() => new JsonResult(DataFilters);

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

Error Occurred While Transmitting JSON Data to the Server

I am trying to send JSON data to my controller's POST handler from the client side: var userName = $('#userName').val(); var password = $('#password').val(); var mail = $('#mail').val(); var admin =$("#admin").is(': ...

Exploring the canDeactivateFn syntax with Angular Documentation

As a first-year university student, I recently discovered that the canDeactivate() guard in Angular is deprecated, while the canDeactivateFn guard functions without any issues. Admittedly, navigating through official documentation is still new to me. From ...

Whenever attempting to utilize my login button in Swift, I often find myself having to press it twice in order for it to successfully connect with the mySQL

I'm in the process of developing an application that requires users to log in and register. When a user successfully registers, their account information is stored in my MySQL database. However, when I try to test the login feature, I encounter an iss ...

Troubleshooting issue: JSON.stringify function returning 'undefined'

Having some trouble with JSON in JavaScript. I've been using JSON.stringify without issue until now. But suddenly, when I try to use it in my application, I keep getting this error in the console (Google Chrome): Uncaught TypeError: undefined is not ...

Auto-populate AngularJS form using PHP array via JSON and $http

I came across a fantastic autocomplete feature in this plunker that I need to replicate using a PHP array with $http. When I tried adding an alert to check my array, it worked perfectly. However, I'm stuck on how to implement the filter in AngularJS. ...

Energizing Evolution - Substituting every instance

Attempting to utilize JOLT transformation tool at for a specific task. The goal is to replace all instances of "master" with "7.11". Here is the input data: { "build": [ { "number": "7.11.13898", "branchName": "branch1" }, { ...

After receiving a BehaviorSubject, the application was paused to handle multiple outcomes

I am trying to implement BehaviorSubject for handling my login user. I have a user BehaviorSubject that returns an observable. get IsAuthenticated() { return this.user.asObservable().pipe(switchMap(res => { if (res != null) { return of(true); } ...

MySQL integration with .NET Core

After watching videos of people successfully using other database systems with .NET Core, I decided to integrate MySQL into my app. However, I encountered an exception when I added the following line to my ConfigureServices method. services.AddEntityFrame ...

Tips for solving the error "Angular CLI version 7.0.3 cannot install node-sass"

Every time I attempt to run npm start, an error message stating that it cannot find the module node-sass appears. Then, when I try running npm install node-sass --save, a series of errors pop up. https://i.stack.imgur.com/2I7DU.png ...

The specified 'Promise<Modules>' type argument cannot be assigned to the parameter of type '(params: any) => Promise<Modules>' in the current context

Looking for some help with this helper function that I need to call, it has the following signature: export const fetchPaginated = async <T>( callback: (params: any) => Promise<T>, { page = 1, pageSize, }: { page?: number; page ...

The jQuery ajax post with dataType set to 'JSON' functions properly on Android devices but encounters errors on iPhone 4

I've encountered a strange issue while developing a phonegap application that connects to my web service. The code works perfectly on Android, but for some reason, it fails on iPhone. It's using jQuery and here is the specific part of the code ca ...

How can I create an input field in MUI that restricts input to letters, numbers, and dashes

Is there a way to configure an MUI input field so that it only accepts letters, numbers, and dashes while excluding spaces and symbols such as (*&^%$#@!,.<>{}[])? Specifically, I want to allow characters that wouldn't disrupt a URL, like . Tha ...

When EJS fails to render a variable even though it has been defined, the error message "Cannot read property '' of undefined" occurs

Experiencing a puzzling issue that needs resolving: I'm currently working with the latest version of node.js, using express, mongo, and EJS. Despite encountering an error in the console, the website continues to function as expected. Cannot read prop ...

Three-dimensional.js and components of the design

Looking for advice on how to manipulate individual parts of a 3D model in Three.js. My model is made up of various components that I need to control separately. Any tips or suggestions would be greatly appreciated. Thank you! ...

Deciphering Google spreadsheet's JSON response into a PHP array: A step-by-step guide

I recently encountered an issue with my Google Docs Spreadsheet call, where the JSON response I received was not fully parsed as needed. After analyzing the data, I realized that I only required everything after the "rows" section. To better understand the ...

Exploring the Differences Between Angular 2 Two-Way Data Binding and One-Way

My query pertains to the distinction between Angular 2's two-way and one-way data binding mechanisms. From my understanding, one-way data binding involves data flowing strictly from parent to child. However, this changes when the source of the binding ...

Issue with ADX: unable to view outcomes of consumption when utilizing JSON mappings

After streamlining the original code, I wanted to provide clarity. I decided to create a single-field table: .create table testtbl (dummy: string) Next, I attempted to input a small JSON document directly: .ingest inline into table testtbl with (format=& ...

Transitioning to mui5's sx prop instead of makeStyles is generating a typescript error - none of the overloads match this call when passing an object with

I encountered an issue while converting a component to mui 5. Here is the original code snippet: const useStyles = makeStyles({ imageContainer: { display: "flex", width: "65%", float: "left", marginRight ...

Querying data in Postgresql 9.4 using the JSONB data type based on a specified date

Transitioning from Mongodb, I am exploring how to select by range using jsonb type. I have approximately 2,880,000 records per day and need to query the database based on station and date fields. While I understand how to select by time range: SELECT * FR ...

Angular Material Progress Spinner is static and not animated

I've been attempting to incorporate an indeterminate spinner from Angular Material. After reviewing the stack blitz example provided on their official website https://stackblitz.com/angular/nkabnxaenep, I carefully compared the package jsons and could ...