What is the best way to iterate over an Angular HTTP Response?

As a newcomer to Angular, I am working on mastering the process of uploading files and calling an API for validation. The API responds with a list of JSON validation errors based on specific file values.

I am currently struggling to iterate through these responses and display them to the user effectively.

After experimenting with map/pipe/subscribe, I have found that the subscribe function provides the most insight into the values being returned. However, I am unsure how to display these values properly instead of [Object, Object].

In addition, I want to ensure that I am following best practices but feel uncertain about my approach in this situation.

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

https://i.stack.imgur.com/4bByQ.png

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

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

What steps should I take once my POST code is returned?

this.httpClient.post(this.PartsAPIURL, formData, { headers: headers })
      .subscribe(event => {
        this.submissionResult = event;
        console.log(this.submissionResult);
        //what to do here?
    });

Furthermore, how can I integrate this with the HTML response?

<p>{{submissionResult}}</p>

Below are examples of failed attempts at handling the response:

An attempt to assign to an array variable

this.httpClient.post(this.PartsAPIURL, formData, { headers: headers })
      .subscribe(event => {
        //fails because the validationErrors and subcategoryErrors are not initialized properly
        this.UploadResponse.validationErrors = event["validation_errors"];
        this.UploadResponse.subcategoryErrors = event["subcategory_errors"];
        console.log(this.UploadResponse.validationErrors);
        console.log(this.UploadResponse.subcategoryErrors);
    });

A snippet that does not return anything - no console statements present

this.httpClient.post<PartsUploadResponse>(this.PartsAPIURL, formData, { headers: headers })
      .pipe(
        map(data => {
          console.log(data)
          this.UploadResponse.subcategoryErrors = data['subcategoryErrors'];
          this.UploadResponse.validationErrors = data['validationErrors'];
          console.log(this.UploadResponse);
        }));

Response class structure

export class PartsUploadResponse {
  public validationErrors: any;
  public subcategoryErrors:any;

}

Thank you for your support!

Answer №1

To ensure accurate responses, let's establish the response type for TypeScript compiler to detect mistakes:

type ErrorResponse = {
  subcategory_errors: ErrorList[],
  validation_errors: ErrorList[]
}

type ErrorList = {
  sheet: string,
  errors: string[]
}

You can store the error lists in local variables as shown below:

subcategoryErrors: ErrorList[] = [];
validationErrors: ErrorList[] = [];

ngOnInit() {
  this.httpClient.post(this.PartsAPIURL, formData, { headers: headers })
      .subscribe((data: ErrorResponse) => {
        this.subcategoryErrors = data.subcategory_errors;
        this.validationErrors = data.validation_errors;
    });
}

For iterating through an array and displaying HTML, utilize the *ngFor directive. Use ng-container to group multiple HTML elements without adding an additional div.

<h1>Subcategory Errors></h1>
<ng-container *ngFor="let errorList of subcategoryErrors">
  <h2>{{ errorList.sheet }}</h2>
  <p *ngFor="let error of errorList.errors">{{ error }}</p>
</ng-container>

<h1>Validation Errors></h1>
<ng-container *ngFor="let errorList of validationErrors">
  <h2>{{ errorList.sheet }}</h2>
  <p *ngFor="let error of errorList.errors">{{ error }}</p>
</ng-container>

Answer №2

Initially, the code that incorporates pipe/map operators is accurate. However, it is important to note that these operators do not initiate a call to the api by default. To make the call, subscribing to the observable returned from the http post method is essential.

Upon subscribing to the observable retrieved from the http post, you will receive the object from the API which can then be bound to the html.

Here is an example of TypeScript code for reference:

this.httpClient.post<any>(this.PartsAPIURL, formData, { headers: headers })
      .subscribe(result=> {
        this.submissionResult = result;
        console.log(this.submissionResult);
        //additional actions needed here
    });

The issue of displaying 'object object' typically arises when there are errors in implementing the HTML layout effectively. The HTML structure needs to be configured properly in order to display all properties within the submissionResult object.

To exhibit the inner properties of the object correctly, specific elements should be added to the HTML markup as demonstrated below:

HTML representation:

<p *ngIf="submissionResult">
    <div *ngFor="let validErrors of submissionResult.validationErrors">
      <div *ngFor="let error of validErrors">
         <span>{{error}}</span>
     </div>
   </div>
</p>

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

The absence of essential DOM types in a TypeScript project is causing issues

Recently, I've been working on setting up a web app in TypeScript but I seem to be missing some essential types that are required. Every time I compile using npm run build, it keeps throwing errors like: Error TS2304: Cannot find name 'HTMLEleme ...

Having trouble getting the onClick function to work in your Next.js/React component?

Recently, I delved into using next-auth for the first time and encountered an issue where my login and logout buttons' onClick functions stopped working when I resumed work on my project the next day. Strangely, nothing is being logged to the console. ...

Encountering an issue with unexpected token 'import' while working on Angular-cli and RC

Currently, I'm in the process of setting up Material 2 with Angular-cli RC5. However, when attempting to load the material button component in app.module.ts, I encounter the following error message. zone.js:461 Unhandled Promise rejection: SyntaxErro ...

The dynamic dropdowns in FormArray are experiencing issues with loading data correctly

Having trouble fetching data for selected country states using FormArray Index. The API keeps getting called every time the country code is passed to retrieve the data. Here's what I've tried, <form [formGroup]='formName'> ...

Is it possible for anyone to access a website's source code using a web browser?

As I navigate the complex world of storing authentication tokens securely using Angular, with the added layer of encryption in the front end before placing it in browser local storage to prevent unauthorized decoding, I have encountered various conflicting ...

What is the best way to display a custom row overlay in ag-grid?

I am looking to display a customized message when no users are found using ag-grid in Angular6. Below is the code snippet: ngOnInit() { this.gridOptions.frameworkComponents.loadingCellRenderer = TableLoadingComponent; this.rowBuffer = 0; this.rowSel ...

AngularJS Constants in TypeScript using CommonJS modules

Let's talk about a scenario where I need to select a filter object to build. The filters are stored in an array: app.constant("filters", () => <IFilterList>[ (value, label) => <IFilterObject>{ value: value, label: label } ]); i ...

Check to see if the upcoming birthday falls within the next week

I'm trying to decide whether or not to display a tag for an upcoming birthday using this boolean logic, but I'm a bit confused. const birthDayDate = new Date('1997-09-20'); const now = new Date(); const today = new Date(now.getFullYear( ...

Demonstrating reactivity: updating an array property based on a window event

One example scenario involves setting specific elements to have an active class by assigning the property "active" as true (using v-bind:class). This property is modified within a foreach loop, after certain conditions are met, through the method "handleSc ...

What is the most effective method for sorting through vast amounts of data with Javascript, React, and Redux?

Currently, I am working with a minimum JSON data set of 90k [...] and utilizing the .filter method. Everything is functioning correctly without any issues, however, from a performance standpoint, I am curious about potential improvements. Any suggestions o ...

Displaying multiple lines of text in a MatSnackbar in Angular is possible

For instance: let message: example;let message2 : example3; For Example: alert(message + '\n'+ message2); Is it possible to display the mat snackbar in Angular in a similar way as shown above?                     ...

Verify if an object property is called with the toHaveBeenCalledWith() function in Jasmine

Recently started incorporating Jasmine into my workflow and I am trying to verify if my method was called with an object that includes a MyProperty property. Currently, my setup looks like this: expect(service['method']).toHaveBeenCalledWith(jasm ...

A guide on mapping an array and removing the associated element

I have an array called responseData, which is used to display the available card options on the screen. public responseData = [ { id: 1399, pessoa_id: 75898, created_at: '2022-11-08T16:59:59.000000Z', holder: 'LEONARDO ', validade: ...

Is it possible to dynamically insert additional fields when a button is clicked?

My FormGroup is shown below: this.productGroup = this.fb.group({ name: ['', Validators.compose([Validators.required, Validators.maxLength(80)])], desc: ['', Validators.maxLength(3000)], category: ['', Validators.require ...

What is the best method for saving this object to an SQL database?

As a newcomer to this game, I am curious to know if it's feasible to store the following object in a single column within an SQL database like postgres: { "foo1": ["bar1", "bar2"], "foo2": [" ...

Component library's Angular 7 Package dependencies

After developing a component library in Angular 7, I encountered an issue when trying to port it to other applications. Even though the Angular library was installed within the component library, it wasn't being bundled with the components for use in ...

Understanding JavaScript Prototypal Inheritance within ES5 Classes

I've been working on creating an XMLHttpRequest interceptor for Angular, encountering a roadblock when trying to intercept a third-party library that uses the XMLHttpRequest API. Although the solution below is functional, I've run into issues wit ...

Angular/TypeScript restricts object literals to declaring properties that are known and defined

I received an error message: Type '{ quantity: number; }' is not assignable to type 'Partial<EditOrderConfirmModalComponent>'. Object literal may only specify known properties, and 'quantity' does not exist in type &ap ...

Instructions for disabling editing for a specific cell within an inline editable row in primeNG

I am currently using PrimeNG DataTable with Angular, where the rows are editable as shown in the example in the documentation: https://www.primefaces.org/primeng/#/table/edit. However, I am facing an issue where I want to exclude one cell from being editab ...

Having trouble accessing the theme in a styled component with @emotion/styled

https://i.stack.imgur.com/zHLON.png I've been using @emotion/react for theming and successfully injected the theme into it. I can access the theme using useTheme within components, but I'm facing some difficulties in accessing the theme within s ...