Leverage ngrx-effect for invoking a service upon an action trigger

Exploring effects in my project, I am working on implementing a warning notification when a search operation fails. The actions related to search are defined like this:

 export enum SearchActionTypes {
  SearchActionSearch = '[Search] Action search',
  SearchActionFulfilled = '[Search] Action search fulfilled',
  SearchActionFailed = '[Search] Action search failed',
}

Incorporated within my application is a service capable of displaying notifications. My objective is to invoke this service when a 'SearchActionFailed' action is triggered. However, I am currently unsure how to construct the effect for this task. Presently, here is where I stand:

    @Injectable()
export class NotificationEffects {
    @Effect()
    // Triggering error notification for invalid search inputs
    searchFailEffect = this.actions$.pipe(
        ofType(Search.SearchActionTypes.SearchActionFailed),
    );

    constructor(private actions$: Actions,
        private notificationService: NotificationService) {}
}

The desired behavior is to utilize the notification service API upon detection of the specified action by the effect. The function call should follow this structure:

this.notificationService.createNotification('type', 'message'))

No specific data is required from the action payload; merely an invocation of the service upon detection of the failure action. Nevertheless, structuring this effect presents a challenge as it necessitates returning an observable, even though no data extraction is needed - just a signal to prompt the service in alerting the user about the erroneous input.

Answer №1

To capture the createNotification's emission, simply include switchMap in your pipe:

searchFailEffect = this.actions$.pipe(
    ofType(Search.SearchActionTypes.SearchActionFailed),
    switchMap(() => this.notificationService.createNotification('type', 'message')))
    .subscribe(x=>console.log(x)); //receive emission from notificationService

If you only need to perform an action without caring about the result (a "side effect"), use .tap():

searchFailEffect = this.actions$.pipe(
    ofType(Search.SearchActionTypes.SearchActionFailed),
    tap(() => this.notificationService.createNotification('type', 'message')))
    .subscribe(x=>console.log(x)); //get emissions of ofType

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

Encountered an issue when attempting to include the "for" attribute to a label within an angular 2.0 template

I am currently using Angular 2.0 framework and working on developing an input component. In addition to that, I am also utilizing Google MDL which requires a specific HTML structure with labels for inputs. However, when trying to implement this, I encounte ...

Adjusting the interface of a third-party TypeScript library

I am currently working on modifying a third-party interface. I'm curious about why this particular code is successful: import { LoadableComponentMethods as OldLoadableComponentMethods } from '@loadable/component'; declare module "load ...

The repository's dependencies remain unresolved by Nest

I encountered an error in my nestjs application. Unfortunately, I am having trouble identifying the issue within my code snippet. Here is a glimpse of the relevant sections: AppModule import { Module } from '@nestjs/common'; import { TypeOrmMod ...

Guide on utilizing the useContext hook in React/Next.js while incorporating TypeScript

As I embark on my journey in the world of TypeScript, I find myself working on a new project in Next.js using TypeScript. My goal is to incorporate authentication functionality into this project by utilizing createContext. Coming from a background in JavaS ...

using the ng2-accordion component in your Angular 2 project

I am having trouble with the angular-2 accordion I implemented. It is not functioning properly and throwing a 404 error. The issue seems to be related to a third-party plugin called "ng2-accordion." I have double-checked the path of the package and it is ...

Changing the name of a tab within a p-tabview

Setting up a p-tabview with tabs containing specific content involves the following code: <p-tabView class="tabmain" > <ng-container *ngFor="let tab of tabs"> <p-tabPanel [header]="tab.header" > ...

Is combining a string and a React element within the same array considered acceptable in the world of React?

Consider a scenario where you need to display data in the form of string[][]. Here is the code snippet: export interface IProps { correctAnswers: string[][]; } public render(): JSX.Element { return ( <div> {this.props.c ...

What method is the most effective for facilitating communication between Angular-Dart components?

While looking for the most effective way to send messages between components in dart-angular applications, I came across some confusion. In previous versions, ScopeAware was used for this purpose, as demonstrated in this thread: Angular Dart component even ...

What is the correct way to specify an image path for a background URL?

Currently, I am setting a background image for the hr tag using the following code: <hr style="height:6px;background: url(http://ibrahimjabbari.com/english/images/hr-11.png) repeat-x 0 0;border: 0;margin:0px!important"> However, I have now saved th ...

The ES Module's require() function is not supported. Please update to dynamic import() instead, which is compatible with all CommonJS modules

I'm encountering some difficulties with launching my Angular application. After running ng serve, I am seeing the following error message: An unhandled exception occurred: require() of ES Module C:\Users\******\Documents\GitHub&bso ...

Increase progress by pressing a button

I've implemented the NgCircleProgressModule library to display a circle with a percentage value in the center. It seems that the progress value remains static and only updates when the buttons are clicked. Clicking on the 25% button within the circl ...

Error message: "Uncaught TypeError in NextJS caused by issues with UseStates and Array

For quite some time now, I've been facing an issue while attempting to map an array in my NextJS project. The particular error that keeps popping up is: ⨯ src\app\delivery\cart\page.tsx (30:9) @ map ⨯ TypeError: Cannot read pr ...

While not all attributes of the response object are null, there are certain object attributes that are displayed as null

My component is responsible for displaying data in a table that is fetched from Firestore. Although the data retrieved is complete, I am noticing that the settings attribute is often null when accessed in JSX. Occasionally, I do see the correct output, but ...

What is the best way to transfer a variable from Django to Typescript?

Within my Django project, there is a template file that I have created: The content of my_template.html: <script> let configuration = '{{ my_config_variable }}'; </script> <script src="{% static 'script.js' %}"></ ...

choose to display on mobile devices as a dropdown menu rather than a modal window

On mobile devices, my select elements are currently displayed as modals with options. However, I need to change this appearance to resemble the dropdown list view observed on desktop devices. Your assistance is greatly appreciated. ...

Application Initialization Error: appInits is not a valid function

When my Angular v17 application starts, I need to set some important values right away. This is how it's done in app.config.ts: export const appConfig: ApplicationConfig = { providers: [ ConfigService, ... { pr ...

Discovering the complete URL utilized to load the application

I am working on an Angular application and I am looking to retrieve the full URL of the application from within the code - specifically, the complete address that the user entered into their browser to access the app. When using Router or ActivatedRoute i ...

Using Angular 8 for Filtering Firebase Data

I need to implement a filter on the titles of my stored data, but I am facing an issue where the structure of the filtered data changes. The original "key" of the data gets deleted by the filter and is replaced with an index instead. Link to repository : ...

Angular obtains an undefined response from a service

Having trouble retrieving the data from my service. Working with Angular 8. Here's the code snippet: Within the service: query(url: string) { this.subscription = this.socket$.subscribe( (message) => { return message; }, ...

Tips for generating a dynamic JavaScript object that contains a function as its value

I am in search of a dynamic method to generate Quasar Table column definitions. While the existing method shown below does work, I believe that replacing the lengthy switch statement with a for loop would be a more efficient solution. How can I implement ...