How can you proceed with a loop in Angular even after receiving a 404 response?

I couldn't find a solution on how to handle the 404 response within a loop in Angular, so I'm reaching out for help here.

Here's the code snippet I'm working with:

for(let order of orders){
    this.api.getURL(order.resource_url).then(data =>
        this.detail = data;
    );
    // Do something with this.detail ...
}

If the request returns a 404 response, I need the loop to move on to the next order and check for a valid response. Any suggestions on how to achieve this?

Answer №1

When the server responds with a 404 error, an exception is thrown. To prevent this, you need to handle the error:

for(let order of orders){
  this.api.getURL(order.resource_url).then(data => {
    this.detail = data;
  }, error => {
    // The error has been handled
  });
}

UPDATE

You may be facing difficulties because you are attempting to utilize an asynchronous API synchronously :) Consider filtering out failed responses before proceeding with your computations:

Promise.all(
 orders.map(order => this.api.getURL(order.resource_url).catch(() => null))
).then(responses => {
  const successfulResponses = responses.filter(response => response != null)
  for(let data of successfulResponses) {
    // Continue with your code here
  }
});

Answer №2

According to shumih, it is important to identify and address the error in order to proceed effectively. In the event of an error, you can use the continue; statement to skip to the next iteration of your loop. Specifically, the line: this.detail = data should not be run if a 404 error occurs because no promise is returned, preventing it from entering the then({}) section.

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 object { production: boolean; } does not include the property 'firebase'

While attempting to deploy my Angular 4 app on both Firebase and Heroku for production, I encountered the following error: ERROR in /Users/.../... (57,49): Property 'firebase' does not exist on type '{ production: boolean; }'. This ...

Utilizing Angular Universal on an existing Express server for enhanced functionality

I have an Express server set up to host my Angular application as static content, along with other functionalities. However, I now want to integrate Server-side Rendering using Angular Universal, which requires a separate Express server just for serving th ...

Is there a TypeScript rule called "no-function-constructor-with-string-args" that needs an example?

The description provided at this link is concise: Avoid using the Function constructor with a string argument to define the function body This might also apply to the rule missing-optional-annotation: A parameter that comes after one or more optiona ...

Sending JSON Object using NavController

I am trying to send a JSON Object to another Page in my Ionic 2 application. However, when I attempt to do so, I encounter the error: Cannot read property 'user' of undefined. While researching for a solution, I came across a similar question ...

Error: ngModel does not reflect dynamic changes in value

After calling a Spring service, I am receiving JSON data which is stored in the "etapaData" variable. 0: id: 266 aplicacao: {id: 192, nome: "Sistema de Cadastro", checked: false} erro: {id: 220, nome: "Falta de orçamento", checked: false} perfil: {id: 8, ...

Displaying a dynamic menu using Angular's ngFor loop

I am attempting to create a menu with sub-menus. The desired structure for my menu is outlined below. However, the demo I'm testing is not producing the correct structure. Check out the demo here. "Sub Test": { // Main menu "Example1":"hai",//sub ...

The issue of Eslint flagging a no-unused-vars error when actually using an interface in a

Currently, I'm working with Vue along with Vue CLI and Typescript. I have imported an interface from a Vuex file and utilized it for type annotation in mapState. However, I am encountering an error flagged by eslint. 'State' is defined ...

Obtaining undefined values for req and resolvedUrl in GetServerSideProps function

In my project, I am currently using next.js version ""next": "^12.1.4"" and node version ""@types/node": "^14.14.6". I have created a function called getServerSideProps with parameters req and resolvedUrl. When the ...

Setting up admin credentials with TypeScript in Firebase cloud functions

While working with Firebase cloud functions in JavaScript, I utilized the following code snippet to initialize admin: admin.initializeApp({ credential: admin.credential.cert(require('./key/firebase-adminsdk.json')), databaseURL: "https://app ...

Angular: Retrieve the source after navigating

Hello there, I am facing a simple problem. I have 2 components navigating to 1 component and in that one component, I need to distinguish which component the navigation came from so I can take appropriate action (such as refreshing a list). The issue is t ...

Error encountered: Uncaught SyntaxError - An unexpected token '<' was found while matching all routes within the Next.js middleware

I am implementing a code in the middleware.ts file to redirect users to specific pages based on their role. Here is the code snippet: import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' import { get ...

Tips on fixing the "TypeError: Cannot read properties of undefined (reading 'lookup')" error message that occurs when running npm install

After successfully running npm install on a freshly cloned Angular project, I encountered an error with the node_modules when trying to launch the application using ng s. Could this issue be related to the version of Node.js being used? \node_modules& ...

Can a unique intrinsic type be created from scratch?

Ever since template literals were introduced in Typescript (PR), we've had access to various useful functions in our types: Uppercase Lowercase Capitalize Uncapitalize For more information, refer to the official documentation. Although it may seem ...

Using an async option value in Angular passing technique

Here is what we see: <select name="day" (change)="showHourRange(value)"> <option selected="true" disabled="disabled">Choose one</option> <option *ngFor="let delivery of deliveries$ | async" [value]="delivery.day">{{de ...

Oops! Looks like there's a problem with the syntax - the import statement can't be

I encountered an error while trying to create Sequelize migrations in my Node.js app (which is set up with Typescript). When running npx sequelize-cli db:migrate, I received an "import method" error, but I'm unable to pinpoint the source of this issue ...

*ngIf condition not met within tr tag and needs to be updated

Within my HTML table, I am using an ngIf statement that relies on the result of a function which is triggered by a click event (toggle(data.code)). Here's a snippet of my code: *TableData contains multiple records <tbody *ngFor="let data of TableD ...

The implementation of CommonJS modules allows for efficient modularization

While using Nx for my Angular workspace, I noticed something that sparked a question in my mind. Why is it necessary to use CommonJS modules in all tsconfig.spec.json files for libs? Looking at Nx examples, I observed that not all libs include it, only app ...

Setting state dynamically in Typescript with ReactJS

Within my state, I have defined this interface: interface State { id: string; name: string; description: string; dimensionID: string; file: File | null; operator: string; isFormValid: boolean; filename: string; }; To handle changes, I&apo ...

The return value depends on the type of function argument passed

I am currently developing a type-safe JSON:API specification parser for handling API responses that can either contain a single object or an array of objects (). For example, when making a request like GET /article: { data: { type: 'article&ap ...

Best practices for accessing session values in Angular 8's Oninit lifecycle hook

When I log in, I store the access token on session storage and try to access it in other components using the oninit() method. However, I keep getting a null value. Upon checking the console, I can see that the token is being stored in the session. Here i ...