Angular Rxjs: A Guide to Calling an Array of Multiple Async Methods

I created a Base Validator method with a list of ivalidator.

import { IValidator, ValidatorModel } from "../validation/ivalidator";
import { Observable } from "rxjs/Observable";

export abstract class BaseValidator implements IValidator {

    private validators = new Array<IValidator>();

    //Validators are pushed to the base validator =>Not implemented yet

    validate(): Observable<ValidatorModel> {

        for (let i = 0; i < this.validators.length; i++) {
            //How do I iterate through all the validators and call their ASYNC method 
            //one by one and stop when there is an error ???
        }

    }
}

Each validator method has a validate() function that returns an observable.

export interface IValidator {
    validate(): Observable<ValidatorModel>;
}

The ValidatorModel looks like this:

export class ValidatorModel {
    readonly isSuccessful: boolean;
    errors: Array<string>;
}

My main concern is :

How can I loop through all the validators and call their ASYNC methods one by one, stopping when an error occurs?

Answer №1

In order for your validations to be run sequentially, you can utilize the merge operator:

validate(): Observable<ValidatorModel> {
    let obs = this.validators.map(validator=>validator.validate());
    return Observable.merge(obs);
}

If you prefer to have your validations executed concurrently, use the forkJoin operator:

validate(): Observable<ValidatorModel> {
    let obs = this.validators.map(validator=>validator.validate());
    return Observable.forkJoin(obs);
}

When it comes to handling errors, both merge and forkJoin will throw an error if encountered, which can then be managed within your subscribe() function. If you are chaining more operations to the Observable<ValidatorModel>, any errors will propagate up the chain:

someValidator.subscribe(
            (results) => {
            },
            (error) => {
                //handle error here
            },
            () => {
                //observable completed
            })

If you wish to explicitly handle errors in your base class, consider using the catch operator:

return Observable.forkJoin(obs)
    .catch(error=>{
        console.log('error encountered',error);
        //handle your errors here
        //Return an empty Observable to terminate the stream
        return Observable.empty();
    });

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

A versatile function capable of invoking two APIs simultaneously, with one of them being designed to return an array

Here is the code snippet that I am working with: getElements(apiUrl: string): Observable<Element[]> { return this.httpClient.get<any>(apiUrl + 'test/elements').pipe( catchError(error => { if(error.status === ...

AInspector WCAG evaluation found that mat-select does not meet level A compliance standards

As I work on making my website WCAG level A compliant, I've encountered an issue with the mat-select component in Angular material. After running checks with the AInspector extension for Firefox, it appears that the mat-select component lacks aria-con ...

Setting up a reverse proxy for Karma during Angular testing is essential for ensuring that

When developing my application, I rely on a backend web service for API calls. I have successfully configured a reverse proxy for the Angular CLI server using the command ng serve --proxy-config proxy.config.json. Everything works fine in this setup. Howe ...

Is there a way to ensure that in angular 2+, when clicking on a button with the same route as the current page, the page will reload?

Why would I even consider complaining about this? You’re already here, aren’t you? I have a couple of reasons why a reload needs to happen, but for now I’ll just mention one. 1) When my user clicks on a link, they may not realize it's the same ...

Discovering the country associated with a country code using ngx-intl-tel-input

In my application, I am trying to implement a phone number field using this StackBlitz link. However, I have observed that it is not possible to search for a country by typing the country code (e.g., +231) in the country search dropdown. When I type a coun ...

Incorporating observables into an existing axios post request

Currently, I have an API using axios to send HTTP POST requests. These requests contain logs that are stored in a file. The entire log is sent at once when a user signs into the system. Now, I've been instructed to modify the code by incorporating Rx ...

Performing a HTTP GET request in Angular 2 with custom headers

I recently came across some posts discussing how to set headers in a GET request. The code snippet below demonstrates one way to do this: let headers = new Headers({ 'Accept': 'application/json' }); headers.append('Authorization&a ...

Angular - A simple way to conceal a specific row in a mat-table using Angular

I am looking to dynamically hide or show a specific column in a table by clicking on a button. The goal is to hide or delete the weight column when the "hide weight" button is clicked, and then show the weight column when the "show weight" button is clicke ...

Deploying a Meteor and Angular2 application to Heroku

Currently working on an app using Meteor, Angular2 with the angular-meteor package, Typescript, and MongoDB. Running into issues while trying to deploy it on Heroku. Utilizing the meteor buildpack from jordansissel/heroku-buildpack-meteor. Uncertain whethe ...

Vite encounters issues when using PNPM because of import analysis on the `node_modules/.pnpm` package

When utilizing PNPM and Vite in a monorepo, I encountered a perplexing issue. The email addresses appearing like `<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0b6a9b4a580f4eef4eef9">[email protected]</a>_@<a ...

When using ngModel, the Tinymce Angular 2+ templates do not initially replace values, whereas they do when templates are inserted by the user

In my Angular 7 app, I am utilizing the TinyMCE editor component. When I insert a template variable into the editor: <span class="data-variable">${variable_name}</span> The variable gets replaced successfully with a value from the `template_r ...

"Proper Installation of Angular Project Dependencies: A Step-by-Step

Whenever I clone an Angular project with older versions that are missing the node_modules folder, and then run npm install to install all necessary dependencies, I end up receiving numerous warnings and errors related to version mismatches. Here are some ...

I am encountering an issue with my testing.spec.ts file. The error message states that XHRs cannot be made from within a fake async test. The request URL causing the problem is http://xxxxxx

After running a test on my service, I encountered the following error: Issue Encountered: Error: Cannot make XHRs from within a fake async test. Request URL: Test File it('should return reasonable json ssss', inject([ProductService, MockBa ...

An error occurred: Unable to access the 'basemapLayer' property due to it being undefined

Oops! TypeError: Unable to access 'basemapLayer' property of undefined I recently put together a simple application using the Angular CLI. After successfully building and running the application with ng serve -o, I encountered an issue in Chrome ...

Struggling to mimic a service in Angular for testing, yet encountering the error message "HTTPClient provider not found."

I am currently working on setting up test cases for an Angular project within my Home Component. The component relies on an ApiCallService, and I am attempting to create a mock for testing purposes. However, I am encountering a persistent error. While th ...

Combine and modify an object coming from a different component

Recently, I developed a customized viewer component specifically designed to showcase song sheets. One of my main objectives is to give users the ability to adjust font settings and other display preferences at their discretion. In order to accomplish this ...

Learning to interpret JSON data retrieved from a RESTful API with Angular

Currently delving into the basics of Angular, I have embarked on a small project. Utilizing JSONPlaceholder, a fake REST API, my goal is to retrieve all posts and display them on a webpage through a straightforward ngFor loop. For this purpose, I have devi ...

The backend built on .Net5 is consistently receiving requests with empty

Having developed a basic server using .Net5 and an Angular frontend, I encountered an issue with my API. It seems to only work properly when the Content-Type is set to application/x-www-form-urlencoded in Postman. However, when I try using application/json ...

What is the best way to make API calls in Angular that avoid caching the response while utilizing a service worker?

Attached are two images. The first image depicts the initial loading of the website with the service-worker being registered. Two arrow marks indicate 302 found and the setting of session information cookies. https://i.sstatic.net/aBO1W.jpg In the second ...

What is the ideal method to manage API post requests in Angular?

I have a requirement to search for a document based on its name property by providing a string input from my Angular application. This involves calling a REST API endpoint with a function that resembles the following code snippet: exports.idea_search = f ...