Angular redirection caused by the NgrX influence

How can I achieve the following effect?

  createAssignment$ = createEffect(() =>
    this.action$.pipe(
      ofType(AssignmentActions.createAssignment),
      switchMap((action) =>
        this.assignmentService.createNewAssignment(action.assignmentTo).pipe(
          map((data) => AssignmentActions.createAssignmentSuccess({ createdAssignment: data }),
            catchError((error) => of(error))),
        )
      )
    ));

I want to redirect the user to a new page based on the value from the 'data' object. Is it better to create a new effect for this or should I handle it directly under the action? Has anyone encountered a similar issue before?

Answer №1

If you want to enhance your code, consider using the tap operator after the map function, which will only be called if the previous operation is successful:

updateUser$ = createEffect(() =>
    this.actions$.pipe(
        ofType(UserActions.updateUser),
        switchMap((action) =>
            this.userService
                .updateUserInfo(action.userInfo)
                .pipe(catchError((error) => of(error)))
        ),
        map((response) => UserActions.updateUserSuccess({ updatedUser: response })),
        tap((response) => { console.log('User updated successfully', response); })
    )
);

Answer №2

I suggest implementing a separate effect for redirection purposes. By creating a new Effect, you can encapsulate its logic and ensure reusability. It is not uncommon to listen for multiple actions in an effect.

  1. Inject the Router in your Effects class assignemnts.effects.ts

    constructor( ... private readonly router: Router) {}

  2. Your Code https://i.sstatic.net/RyO7d.png

Create a Redirect Effect that listens to your AssignmnetActions.CreateAssignemntSuccess({assignment}); Scenario: This effect will extract the user ID from the assignment and redirect to the /user-details page.

userPageRedirect$ = createEffect(() =>
    this.actions$.pipe(
      ofType(AssignmnetActions.CreateAssignemntSuccess()),
      concatMap((action) => of(action).pipe(withLatestFrom(this.store.pipe(select(getSelectedUserId))))),
      fetch({
        run: (action, userId: number) => {
          this.router.navigate([`/user-details/${userId}`]);
        },
      })
    ));

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

Troubleshooting Angular4 and TypeScript Compile Error TS2453: A Comprehensive

I'm facing an issue in my Angular4 project build process which I find quite perplexing. The error seems to be related to the import of certain components such as Response, Headers, and Http from @angular. Whenever I attempt to build my project, it thr ...

Building a versatile setting within a child component by incorporating TypeScript and deriving state data from the parent component

In my page component, I have set a state called formData. Now, I want to create a context within my form component so that I can utilize it in each child form component. Everything works smoothly without TypeScript. However, when using TypeScript, I encoun ...

Step-by-step guide to initializing a project using React with Typescript and a functional server-side script

I am working on a project that involves a React Typescript app (created using Create React App). In this project, I need to have an executable script that can run alongside the React app. Both the app and the script are intended to only run on local machin ...

The selected value of the PrimeNG p-checkbox cannot be determined using a function when binding to [ngModel]

These are the rows of my custom p-table <tr> <td>{{user.userName}}</td> <td>{{use.userSurname}}</td> <td *ngFor="let group of groups"><p-checkbox [(ngModel)]="showVal ...

Utilizing JavaScript recursion to navigate through a JSON object and update specific key-value pairs on its nested children

Exploring a JSON object structure that follows a tree-like child-parent relationship. Each node in the structure has a unique ID. Attempting to iterate through the entire object using a recursive function, encountering challenges with handling the children ...

Tips for iterating over an array that implements either of two interfaces in TypeScript

The objective is to develop a reusable method for filtering out items from an array that implements one of two interfaces Providing a code example would be most helpful: interface IDuration { start: number; end: number; } interface IRelativeDuration ...

Executing MongoDB collection operations with array filtering

I am looking to count records based on tags and filter them before including in specific groups // data in database {tags: ['video', 'Alex'], ... }, {tags: ['video', 'John'], ... }, {tags: ['video', 'J ...

Having trouble setting up the rootReducer using combineReducers

import { combineReducers } from 'redux'; import { reducers } from './reducers'; import { IAppAction } from './action'; import { routerReducer } from 'react-router-redux'; import { IAppState } from './state/app-s ...

Having issues with parameterized URL integration between Django2 and Angular2

I am encountering an issue with integrating a URL containing parameters in Angular and Django. When making a call to the url, Django expects a slash at the end while Angular appends a question mark before the parameters. How can this be resolved? Below is ...

Dealing with checkbox changes in Angular 2

I have a checkbox that is initially checked, and I want to use the (change) event on it. After being clicked, I want to clear the input text for "Activation key". When re-checked, I want to generate a GUID and add it back to the input field. How can I dete ...

Having trouble accessing information from the useSelector hook in Redux

I am able to access the information stored in Redux by using console.log, but I encounter a type error when trying to access specific parts of this information. const profile = useSelector(state => state); console.log(profile); // Successfully prin ...

Utilize Hostbinding in Angular to Inject Style Declarations

Is there a way to efficiently inject multiple style declarations into a component using the @HostBinding decorator? I've been attempting the following: @HostBinding('style') get style(): CSSStyleDeclaration { return { background: &apo ...

Harnessing the power of Heatmaps in Angular 6

Currently, I am developing a data visualization project using angular6. I would greatly appreciate any assistance on how to incorporate heatmaps into the angular6 application. Thank you in advance for your help! ...

Encountered an issue in React Native/Typescript where the module 'react-native' does not export the member 'Pressable'.ts(2305)

I have been struggling to get rid of this persistent error message and I'm not sure where it originates from. Pressable is functioning correctly, but for some reason, there is something in my code that doesn't recognize that. How can I identify t ...

What is the best way to create an optional object parameter in Typescript?

I'm working on a function that looks like this: const func = (arg1: string, { objArg = true }:{ objArg: string }) => { // some code } Is it possible to make the second parameter (an object) optional? ...

Decrease initial loading time for Ionic 3

I have encountered an issue with my Ionic 3 Android application where the startup time is longer than desired, around 4-5 seconds. While this may not be excessive, some users have raised concerns about it. I am confident that there are ways to improve the ...

When accessing APIs, create an array of observables for each user call and then trigger a function once all are successfully resolved

As I aim to generate a list of observables while a user engages with the webpage, I am faced with the challenge of individually subscribing to each observable, but desiring another function to execute after individual or multiple simultaneous API calls are ...

Ideas for structuring the design of Angular 2 with a PHP backend

I'm facing a major project that has evolved significantly over time. I am considering transitioning from jQuery to Angular 2 in the frontend, not just refactoring (this is different from discussions of refactoring jQuery to Angular that have been wide ...

Steps for importing vuetify/lib alongside the vuetify loader in the A-La-Carte system

When utilizing the A-La-Carte system in vuetify with vuetify-loader, I encountered a TypeScript error while trying to import vuetify/lib. I am unsure of what mistake I might be making here and would appreciate some assistance with importing this. I was re ...

What is the process for defining a global variable within a module in Typescript?

I've already included a global value in my global JavaScript context: const fs = require('fs') For a specific reason, I need to include it in the global scope. Now, I want to create a .d.ts file to declare the global variable with a stron ...