Creating a TypeScript NgRx effect for initiating an action

Hello all, I am relatively new to NgRx and so far most of my code is running smoothly. However, I've hit a roadblock with a specific issue and would appreciate some assistance.

The problem I'm facing is related to the Login Effect being triggered successfully and sent to LoginSuccess. I am attempting to save this data to localstorage and then trigger another action.

Below you can find a snippet of my code:

Login Effect

    @Effect({ dispatch: false })
    LogInSuccess$: Observable<any> = this.actions$.pipe(
        ofType<businessActions.LogInSuccess>(
            businessActions.AuthActionTypes.LOGIN_SUCCESS
        ),
        map((action: businessActions.LogInSuccess) => {
            localStorage.setItem('token', JSON.stringify(action.payload));
            this.navCtrl.navigateRoot('/home');
        }), map(
            () => new businessActions.LoadBiz()
        )
    );

Answer №1

It appears that you are attempting to incorporate some UI functionality based on the response from a service (LoginService). The code provided is suitable for a library or service, but ultimately, you must subscribe to the observable at some point to ascertain its result.

Ensure to include a subscribe() call to finalize your observable and obtain the result.

UPDATE

In addition to the subscribe() call, it is essential to navigate to the /home URL and in the corresponding component, execute the business logic using new businessActions.LoadBiz().

Your code structure should resemble this:

@Effect({ dispatch: false })
LogInSuccess$: Observable<any> = this.actions$.pipe(
    ofType<businessActions.LogInSuccess>(
        businessActions.AuthActionTypes.LOGIN_SUCCESS
    ),
    map((action: businessActions.LogInSuccess) => {
        localStorage.setItem('token', JSON.stringify(action.payload));
    })
).subscribe(() => this.navCtrl.navigateRoot('/home'));

Subsequently, within the method that handles the /home route, preferably in the init() function of the component, utilize new businessActions.LoadBiz(). Alternatively, consider organizing the businessActions logic into a service, injecting it, and then calling businessActions.LoadBiz() without requiring the use of new in your UI implementation.

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

Trouble injecting factory into controller using Jasmine and requireJS

I'm encountering some difficulties when trying to inject my factory into testing spec. My setup involves using requireJS to inject controllers and factories. define(['controller', 'loginFactory', 'angular', 'ang ...

What could be causing the error within the 'react-code-blocks' library?

Currently, I am involved in a project that utilizes Typescript and React. However, I have encountered an issue while working with the 'react-code-blocks' library. The structure of my container component is as follows: interface ICodeBlockProps { ...

Conceal the Addon Tab across all pages in Storybook

Is there a way to globally hide an Addon Tab without disabling the addon itself? Specifically, I am using version 5.3.18 of Storybook with React and I want to hide the tab panel from the addon "styled-component theme". I apologize for the basic question, ...

Flipping over every single card, but only desire to flip them one at a time

My attempt to flip these cards individually has resulted in them all flipping together. I suspect there may be an error in my JavaScript code. In the original code, I used images in front and an unordered list in the back, but here I have simplified it t ...

Injecting a service into a parent class in Angular 6 without the need to pass it through the constructor

Can anyone provide guidance on how to incorporate a service with multiple dependencies into an abstract class that will be inherited by several classes, in a more streamlined manner than passing it through all constructors? I attempted to utilize static m ...

Node.js project: The client does not support the authentication protocol requested by the server

Currently facing an obstacle in connecting to a MySQL database that is locally stored on my machine using a node server (also localized). Context / Setup My node project is utilizing typescript, however, I am executing it by utilizing tsc followed by npm ...

Numerous occurrences of Vue-Chartjs

My goal is to incorporate multiple Doughnut type graphs into a single component. Resource: <div class="row"> <div class="col-12 col-lg-6"> <strong>All</strong> <Doughnut chart-id="wor ...

Tips for seamless communication between PHP and JavaScript

While working on my revolutionary WebIDE, I encounter numerous questions that challenge me. The goal of this project is to assist users in quickly developing what they normally would, but automated. One particular question I have is regarding the implement ...

Transferring canvas image from JavaScript to RESTful Web Services via POST method

Recently, I have been working on a project that involves saving canvas images from HTML JavaScript and then uploading them to RESTful web services using JSON. I am facing some challenges in figuring out how to successfully upload canvas images using JSON ...

Looking for a solution to display PHP AJAX errors in my jQuery script?

I am facing an issue with my PHP AJAX code and jQuery integration. The current problem is that the error case in jQuery is consistently being triggered, but I am unsure of the reason behind it. Below is the jQuery code snippet: $('.vote_up').cl ...

Setting up dynamic routing in AngularJS for links

I am facing some confusion regarding routing in AngularJS. Normally, we can configure routes in angular.config() when the angular module is loaded. At that time, we define static information such as routePath, templateUrl, and controller. However, I am u ...

Using a vanilla JS object as a prop for a child component

I have created a custom Message class in my application to handle incoming messages, which is defined in message.js. Within message.js, I've implemented two classes: Message and EventEmit. The render function in my Message class requires passing an E ...

"Enhance Angular 2 by including both a key and value for every item within an

I am working with an array of objects like this: array = [ {name: 'name'}, {name: 'name'}, {name: 'name'}, {name: 'name'}, ] My goal is to add a key called '123' to each object in the array, so i ...

Introducing a new element in TypeScript using a separate method with parameters

Currently, I am attempting to create a method that will allow me to add an element to my array. Despite being new to typescript, I have been struggling to determine what needs to go into the addNewProduct function. While seeking help, I came across the p ...

Using Node.js, iterate over every key-value pair within a Redis hash data structure

I am currently navigating my way through the world of redis and node, attempting to iterate over some test hash keys that I have generated. My goal is to display the results on the screen. The expected output should look like this: { "aaData": [['Tim ...

Ways to modify babel output file extensions

I'm facing an issue where babel --out-file-extension is not working as expected. Below is my package.json : { "name": "Assets", "version": "1.0.0", "description": "", "main" ...

Module ng2-img-tools encountered a metadata version mismatch error

Encountering an error while trying to utilize the ng2-img-tools package in conjunction with Angular4. The specific error message is: ERROR in Metadata version mismatch for module ~/client/node_modules/ng2-img-tools/dist/ng2-img-tools.d.ts, found version 4 ...

What changes can be implemented to convert this function to an asynchronous one?

Is it possible to convert the following function into an asynchronous function? getHandledSheet(): void { this.timesheetService.getAllTimesheets().subscribe({next: (response: TimeSheet[]) => {this.timesheetsHandled = response.filter(sheet => ...

Ensuring strictNullChecks in Typescript is crucial when passing values between functions

When using the --strictNullChecks flag in TypeScript, there seems to be an issue with inferring that an optional property is not undefined when the check occurs in a separate function. (Please refer to the example provided, as articulating this clearly is ...

Leverage React.JS to iterate through arrays and objects, rendering data seamlessly - even within nested objects

Development of Category's Filter component Implementing the rendering of data from a nested array using React Js Although I attempted to render it as seen below, it is not displaying anything The main focus is on the rendering part only var selecte ...