Error encountered: Discrepancy in action type within ngrx effect

I have set up an actions file containing three different actions:

export const showLoading = createAction(`[application] Show warning notification`);
export const hideLoading = createAction(`[application] Show error notification`);
export const showHttpResponseError = createAction(`[application] Show success notification`, props<{ error: HttpErrorResponse, nextAction: Action }>());

export type Actions = ReturnType<
typeof showLoading |
typeof hideLoading |
typeof showHttpResponseError
>;

Following that, I created an effects file structured as follows:

@Injectable()
export class ApplicationEffects
{
    constructor(private actions$: Actions, private dialogsService: DialogsService, public notificationsService: NotificationService, private router: Router) { }

    @Effect() public errorHandler$ = this.actions$
        .pipe(
            ofType(ApplicationActions.showHttpResponseError.type),
            switchMap(action => {
                    const emptyAction = { type: 'noop' };
                    const error = HttpErrorHandler.handle(action.error);

                    if (error.redirectTo != null) {
                        this.router.navigate([error.redirectTo]);
                        return of(emptyAction);
                    }

                    if (action.error.status === 400) {
                        this.notificationsService.notifyWarning('AVISO', error.messages);
                    }
                    else {
                        this.dialogsService.errorDialog('ERRO', error.messages[0]);
                    }

                    return action.nextAction ? of(action.nextAction) : of(emptyAction);
                },
            ));
}

However, I am facing an issue where the VS Code intellisense does not recognize the action type in the switchMap section and labels it as never:

https://i.sstatic.net/dgTox.png

Is there something missing from my setup? How can I enforce the correct type for it, especially since the action is generated using ngrx action creators without a specific type definition?

Answer №1

To provide a comprehensive solution, there are several approaches:

1) Utilize the ofType operator.

ofType<AddAction>(CounterActions.AddAction)

2) Specify the type of injected actions, as mentioned earlier (introduced in NgRx 7).

constructor(private actions$: Actions<CounterActions.Actions>

3) Employ createEffect along with createAction (available from NgRx 8 onwards).

foo$ = createEffect(() => this.actions$.pipe(
    ofType(addAction),
    ...
);

Answer №2

If anyone encounters a similar issue in the future, just remember to reference the injected actions$ variable like this:

private actions$: Actions<ApplicationActions.Actions>

By doing so, you'll have intellisense working properly and won't require specifying a type in the switchMap.

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

Easily retrieve the value of a form control when it is changed with Form

Currently, I am in the process of reviewing Formly. In my initial attempt, I am trying to trigger a method when the content of a textarea changes. The code snippet below shows what I have tried so far. Unfortunately, it seems like the functionality is no ...

Combine Immer and NgRx reducer for improved state management

Upon analyzing redux and ngrx, it appears that immer is the preferred library for creating a copy of the state before storing it. In following the example provided by immer, I implemented the following code in my reducer: on(exampleActions.updateExample ...

Can you explain how NGXS store manages its data storage? Is there a memory limit set for the NGXS store? And where exactly is the NGXS store memory located within the browser

Although I attempted to learn NGRX from their official site, I found myself lacking a clear understanding of where and how the data is stored within NGRX. Additionally, I could not find any information regarding the maximum limit of data that can be stor ...

Building custom queries in ReactQuery with Typescript is a powerful tool for

Currently, I am in the process of creating a simplified query builder for my react query requests, but I am facing challenges with TypeScript. My proficiency in TS is not great as I am still learning. I am attempting to incorporate the latest insights fro ...

Exploring the module and module resolution options in the TypeScript compiler

It seems that many tsconfig.json examples include the compilerOptions section with entries like this: "module": "commonjs", "moduleResolution": "node" Setting both values to commonjs and node respectively may seem r ...

Steps for altering the primary color in PrimeNG__Changing the primary color

What is the most effective way to modify the default primary color for primeNG (saga-blue theme)? Altering --primary-color does not have the desired effect, as elements in node_modules/..../theme.css are styled using the main color hex rather than '-- ...

Publish the file on Angular 7 route for accessibility

I'm currently stuck on an issue that I can't seem to figure out. I'm attempting to link my website to Apple Pay through Stripe's PaymentRequest feature. However, I'm running into difficulties with one of the requirements they have ...

Guide to hosting a Razor partial view within Angular, without using IIS

Exploring an age-old topic on How to utilize ASP.Net MVC View .csthml as Angular View rather than .html I am seeking a similar solution but with Angular 15 and VS Code. My goal is to develop Angular components within VS Code for an ASP.NET MVC site (not W ...

Implementing an automatic logout feature based on the expiration timestamp of a JWT token

My goal is to have the application automatically log out based on an expiry token. Angular Client Code: login(credentials) { return this.http.post('http://something/api/login/', credentials) .map(response => { let res ...

I am encountering a TypeScript error with URLSearchParams. The object cannot be successfully converted to a string using the toString() method

During the development of my react app with postgres, express, node, and typescript, I ran into an issue while working on the backend code. The problem arises when trying to utilize URLSearchParams. index.js import express from 'express'; import ...

Having trouble accessing the object from @Input

My issue revolves around system.component.html <div *ngFor="let tab of tabs | async"> <app-tab [tab]="tab"></app-tab> </div> In tab.component.ts, I wrote the following code: export class TabComponent implements OnInit { @Inpu ...

404 error page in Spring Boot and Angular 6 with white label branding

Currently, I am utilizing Angular 6 in conjunction with Spring Boot. After copying the 'dist' file to my Spring Boot project, everything runs smoothly. However, upon refreshing the browser, I encounter a 'white label error'. How can I p ...

The filtering process of an array using the filter() method is effective, however, it does not result in any visible changes on

script.js searchVideo = (keyword) => { this.input = keyword; if(this.items.length == 0){ this.filteredItems = []; } if(!this.input){ this.filteredItems = this.items; } const args = this ...

Tips for enabling custom tags in the tinyMce editor

<textarea><div style="margin-top: 15px;"> <div class="dropdown "> <p> hello my name is <Enter Your Name> </p> <p> hehe</p> </div> </div> ...

Unable to resolve TypeScript error: Potential 'undefined' object

Here is the code snippet that I am working with: const queryInput = useRef() const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault() if (queryInput && queryInput.current) { console.log(`queryInput.cur ...

Slim 4 with Angular 10: Issues with downloading PDF files through API, as Angular blob response is coming back empty

Struggling to integrate the download PDF Angular API with Slim 4 API. The response from Slim can be seen in the browser network, but when trying to parse it in Angular, it comes back empty. All the necessary headers have been added on both Angular and Slim ...

What is the best method to integrate an external SDK using Java files in a React Native project while still maintaining a clean code

I am working on a React Native CLI project for an Android app and I need to integrate a Java SDK to access certain functions. The problem is that the SDK frequently updates, so I don't want to modify the original Java code directly (and can't use ...

Angular Ant Design Pagination

Currently, I am working on implementing cards and pagination in Angular version 7 using Ant Design. While following the guidelines on the Ant Design website () for cards, I noticed that it does not provide instructions on how to combine cards with pagina ...

Ways to update a prop and reset it to its original state using React Hooks

My goal is to take a string prop text, trim it, and then pass it to the state of a component. I used to achieve this using the componentDidMount function in the past. However, now I am trying to use the useEffect() hook but encountering an error: "Cannot ...

It appears that protractor-flake is programmed to re-run all tests instead of just the ones that have failed

Running tests using the latest version of "[email protected]", encountering failures during testing but the tests are rerunning again. No custom reporter used except Allure reporting. Below is the command used for running: protractor-flake --max-at ...