Receive a failure message from ngrx@effects and pass it to the component

I am encountering an issue with setting up server error validation for each input field in a form. The challenge lies in the fact that I am using ngrx@store, which presents a complication.

 @Effect({ dispatch: false })
  error$ = this.actions$.pipe(
    ofType(actions.UserActionTypes.Error),
    map(
      (error: actions.Error) => {
        new actions.Error(error);
      }
      //this.notificationService.warn(error.error.message)
    )
  );

This code enables me to store errors within the store.

Now, my aim is to retrieve these errors within my component. Subsequently, I intend to identify the input field associated with the error and display the error message next to said field.

    this.errorsMsgs$ = this.store.select(fromStore.UserSelectors.getErrors);
    this.errorsMsgs$.pipe(takeUntil(this.destroy$)).subscribe((error: any) => {
      console.log(error);
      for (let err of error) {
        if (err.field === "username") {
          this.usernameError = err.defaultMessage;
        }
        if (err.field === "lastName") {
          this.lastNameError = err.defaultMessage;
        }
        if (err.field === "firstName") {
          this.firstNameError = err.defaultMessage;
        }
        if (err.field === "email") {
          this.emailError = err.defaultMessage;
        }
        if (err.field === "phone") {
          this.phoneError = err.defaultMessage;
        }
        if (err.field === "enabled") {
          this.enabledError = err.defaultMessage;
        }
      }
    });

The difficulty arises when attempting to implement this code within ngOnInit. This leads to an error in the console due to the unavailability of errors at that stage.

ERROR TypeError: error is not iterable

The CRUD function operates within ngrx@effect, encompassing success and error scenarios. How can I determine in the component when the submit method encounters an error response? Is it possible to trigger this method from the effects?

Here is an example of an error response:

{
  "timestamp": "2020-01-14T11:37:51.533+0000",
  "status": 400,
  "error": "Bad Request",
  "errors": [{...}
  ],
  "message": "Validation failed for object='user'. Error count: 6",
  "path": "/user/add/"
}

Answer №1

To receive updates from the actions observable channel, you can subscribe to it and filter out the desired actions using the ofType() operator function in your component. For example:

ngOnInit(){ this.actions$.pipe(ofType(action)).subscribe(action => console.log(action.payload)); }
. Make sure to inject the actions$ observable in your constructor by importing it from
import { Actions} from '@ngrx/effects';
. If you prefer to store this result, you can use a reducer and then select the desired values from the store.

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

Showing pdf documents without relying on third-party software

Within my Angular application, I have integrated the following snippet into an HTML template: <embed src="../assets/AOK_T2DM.pdf" style="width: 100%;height: 500px" type="application/pdf"> The representation of this code ...

Angular 4: Solving the 'Access-Control-Allow-Origin' issue specifically for post requests

I have searched for solutions to my problem on the topic, but haven't found one that works for me. As a newcomer to Angular 4, I am attempting to create an update/delete service using a custom external API. Initially, I encountered CORS issues which ...

What could cause my arguments to "not align with any signature" of console.log?

Here is a basic class example: export class Logger { constructor(private name: string) {} debug(...args: any[]) { console.debug(...args) } log(...args: any[]) { console.log(...args) } } Despite being able to pass anything to console.l ...

Scroll-triggered Angular 4 sliding functionality

I am struggling to achieve the desired effect. I have successfully set up the @HostListener to detect window:scroll events, but I am unsure how to add a CSS class that animates a div to slide up using CSS animations when scrolling. @HostListener('win ...

Halting external observation using switchmap without finishing internal observations

After conducting a thorough search, I couldn't find a similar question to mine, so I apologize if this has been asked before. In my scenario, I have multiple connected observables working in sequence. One of the observables, let's call it Obser ...

The error message "this.startLoginAnimatioon is not defined as a function" popped up

I've been developing a login system using TypeScript but I keep encountering an error that I can't figure out. Here's the issue in detail: https://i.sstatic.net/PN4N8.png The problem arises when the this.startLoginAnimation() function ...

Access data from JSON array in Angular 2

I'm facing a basic issue here. I have a JSON file named pageDefinition.json that is being loaded into my component. Here's how the JSON data looks: ... "testArray": [ {"id": 0, "name": "row1"}, {"id": 1, "name": "row2"}, {"id": 2, "n ...

Nested *ngFor Loop in Angular 2

I am facing an issue with my classes Produkt and Werbedaten. The werbedaten class includes a produckt array. My goal is to display a werbedaten array containing the Produkts array using *ngFor export class Produkt { public artikelNummer: number; p ...

Unable to import TypeScript modules unless the file extension is explicitly specified

As someone new to TypeScript, I was under the impression that I could import my TS files without specifying their file type. Currently, I have to write: import {sealed} from "./decorators/decorators.ts"; Instead of what I believe should be the correct w ...

Hosted-Git-Info Regular Expression Denial of Service attack

I am facing a vulnerability in my Ionic/Angular app. The issue suggests updating the version of hosted-git-info. However, I cannot find this package in my package.json file. Can you provide guidance on how to resolve this? https://www.npmjs.com/advisorie ...

Challenge with validating a custom form control using Angular's FormArray

Could you please review the following issue? I have developed a custom component that functions as a checklist. I utilized FormArray to represent the rows, making each row a form array item and thus a FormGroup. Below is the form definition for the main ...

How to Create a Flexible Angular Array Input Component

I have been working on developing reusable form input components using Angular's reactive forms. However, I am currently encountering challenges with my FormArray input component. To overcome some issues, I had to resort to using double-type casting ...

Is it possible to retrieve the precise key currently indexed within type declaration?

I am currently working on developing a simple type that would require a nested object key to reference the outer level. For better understanding, let's take an example: const obj = { foo: { name: 'bar', ref: 'foo' // & ...

Adjusting the binding of ngModel within a loop

Apologies, I am having difficulty articulating this issue. I am attempting to display a form that iterates through an array of object keys and generates input fields based on the number of properties an object has. For instance: <form [ngFormModel]=" ...

Navigating to a Different Page in Angular 7

After logging in on my login page, the dashboard component appears below the login page instead of redirecting as a new page. How can I achieve this in Angular 7? Any assistance would be greatly appreciated. Thank you! app.component.ts import { Component ...

The specified property 'XYZ' is not found in the type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'

Whenever I try to access .props in RecipeList.js and Recipe.js, a syntax error occurs. Below is the code snippet for Recipe.js: import React, {Component} from 'react'; import "./Recipe.css"; class Recipe extends Component { // pr ...

Typescript - A guide on updating the value of a key in a Map object

My Map is designed to store Lectures as keys and Arrays of Todos as values. lecturesWithTodos: Map<Lecture, Todos[]> = new Map<Lecture, Todos[]>(); Initially, I set the key in the Map without any value since I will add the Todos later. student ...

Jasmine test confirms that momentJS objects with the same values do not match

In my angular-cli project, I have a set of Jasmine tests that include various assertions. One particular assertion looks like this: expect(dispatchSpy).toHaveBeenCalledWith({ type: 'SET_RANGE', payload: { value: 'Weekly', start: mome ...

What is the best method for displaying file size in a user-friendly format using Angular 6?

Imagine having this snippet in an HTML file: *ngFor="let cell of dateFormat(row)">{{cell | filesize}}</td>, where the dateFormat function looks like this: dateFormat(row:string){ var today = new Date(row[4]); let latest_date = this.date ...

Encountering an error when attempting to iterate over an undefined property using an API

I am trying to fetch all classes and their assignments from Google Classroom. I successfully used Google's example code for listing the classes, but had to write my own code for listing the assignments. While the code runs as expected and lists the as ...