"Customizing API requests based on specific conditions with n

For a specific scenario, I need to login as an admin in one case and as a regular user in another.

  signIn$ = createEffect(() =>
    this.actions$.pipe(
      ofType(AuthActions.signInRequest),
      exhaustMap(({ variables, redirectTo, hasAdmin }) => hasAdmin ?  
        this.authService.signInAdmin(variables) : 
        this.authService.signIn(variables).pipe(
          map((response) => {
            //... AuthActions.signInSuccess(response.token)
          }),
          catchError(() => of(AuthActions.signInFailure()))
        )
      )
    )
  );

Even though the API response is the same for both cases, I encountered the following error:

Type 'Observable<FetchResult<SignInAdmin, Record<string, any>, Record<string, any>> | FetchResult<SignIn, Record<string, any>, Record<...>>>' is not assignable to type 'EffectResult'. Type 'Observable<FetchResult<SignInAdmin, Record<string, any>, Record<string, any>> | FetchResult<SignIn, Record<string, any>, Record<...>>>' is not assignable to type 'Observable'. Type 'FetchResult<SignInAdmin, Record<string, any>, Record <string, any>> | FetchResult<SignIn, Record<string, any>, Record<string, any>>' is not assignable to type 'Action'.

Property 'type' is missing in type 'FetchResult<SignInAdmin, Record<string, any>, Record<string, any>>' but required in type 'Action'.ts(2322) models.d.ts(2, 5): 'type' is declared here.

effect_creator.d.ts(42, 161): The expected type comes from the return type of this signature.

Answer №1

It seems like there may be a missing return value for the success case in your code snippet: Here is a revised version that should work (assuming the authService returns the same type of result for both login cases):

signIn$ = createEffect(() =>
    this.actions$.pipe(
      ofType(AuthActions.signInRequest),
      exhaustMap(({ variables, redirectTo, hasAdmin }) => hasAdmin ?  
        this.authService.signInAdmin(variables) : 
        this.authService.signIn(variables).pipe(
          map((response) => {
            //... AuthActions.signInSuccess(response.token)
          }),
          catchError(() => of(AuthActions.signInFailure()))
        )
      ),
      map(signInResult => AuthActions.signInSuccess({data: signInResult))
    )
  );

Answer №2

Just a heads up for anyone facing a similar issue in the future - I encountered the same problem as described here: Angular Error TS2554:Expected 0 arguments, but got x on piped operators

It seems like the pipe function breaks when trying to accept arguments that don't match the exact interface of the observable being piped on, even if the interfaces share the same properties.

To work around this issue, I made the following adjustment:

      exhaustMap(({ variables, redirectTo, hasAdmin }) => {
        return ((hasAdmin
          ? this.authService.signInAdmin(variables)
          : this.authService.signIn(variables)) as Observable<
          FetchResult<SignInAdmin | SignIn>
        >).pipe(

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

Converting md ElementRef to HtmlElement in Angular 2+: A Step-by-Step Guide

My query is related to retrieving the favorite food input in TypeScript. The input field is defined as: <input mdInput #try placeholder="Favorite food" value="Sushi"> In my TypeScript file, I have accessed this input using: @ViewChild('try ...

You can easily search and select multiple items from a list using checkboxes with Angular and TypeScript's mat elements

I am in need of a specific feature: An input box for text entry along with a multi-select option using checkboxes all in one place. Unfortunately, I have been unable to find any references or resources for implementing these options using the Angular Mat ...

Unable to mock ESM with unstable_mockModule

In my project, I am utilizing ESM. The transpiled .ts files are converted into .js and stored in the 'dist' directory. Here is an example of how my directory structure looks: dist/ ├─ src/ │ ├─ store/ │ │ ├─ index.js │ ├ ...

Discovering and Implementing Background Color Adjustments for Recently Modified or Added Rows with Errors or Blank Cells in a dx-data-grid

What is the process for detecting and applying background color changes to the most recently added or edited row in a dx-data-grid for Angular TS if incorrect data is entered in a cell or if there are empty cells? <dx-data-grid [dataSource]="data ...

The property "property" does not exist within this object

I'm currently developing a peer-to-peer payment system on the Polygon network. I've tried various solutions, such as including any, but none have been successful. Here is the error message I'm encountering: Element implicitly has an 'a ...

How can I populate dropdown options from an API in a react JS project using typescript and react saga?

Check out my page, where I am trying to fetch brand options from an API. Below is the saga I have implemented: Action.tsx export const getBrandsForDropdown = (request: IPagination) => { return { type: actions, payload: request ...

The method of having two consecutive subscribe calls in Angular2 Http

Can the Subscribe method be called twice? I am attempting to create an API factory that stores data in the factory and allows different components to use that data for each AJAX call. The factory: export class api { result = []; constructor (p ...

What is the best way to handle multiple requests to the same URL in Cypress while waiting?

I am currently developing a Cypress test that involves sending multiple requests to the same URL with varying body content. Essentially, the test modifies input values in the user interface, triggering new server requests. The challenge arises when trying ...

Combining Vitest with FastifyAutoload resulted in a FastifyError: The plugin provided must either be a function or a promise, but instead, an 'object' was received

My application built on Fastify ("fastify": "^4.26.0") operates smoothly under normal conditions with no issues. However, when trying to incorporate unit testing using Vitest, every test fails despite their simplicity. Upon troubleshoot ...

Encountered a bun runtime error stating "Possibly require an `extends React.JSX.IntrinsicAttributes` constraint for this type parameter."

I have a good understanding of ReactJS, but this topic seems to be more advanced. I am working with generics in TypeScript and have the following code: export const withPopover = <T,>(WrappedComponent: React.ComponentType<T>) => { const ...

Creating a singleton in TypeScriptWould you like to know how to declare a singleton in

My goal is to incorporate an already existing library into my TypeScript project. The library contains a singleton object that I want to declare and utilize. For example, within the xyz.js file, the following object is defined: var mxUtils = { /* som ...

Determine the consistent type for numerous properties

Is it feasible to have Typescript automatically infer the type of multiple properties to be the same, or even infer the types based on a specific property? For example, consider the following code snippet -> interface Test<T> { value1: T; val ...

Leveraging Leaflet or any JavaScript library alongside Typescript and webpack for enhanced functionality

Important: Despite extensive searching, I have been unable to find a resolution to my issue. My current endeavor involves developing a map library through the extension of leaflet. However, it appears that I am encountering difficulties with utilizing js ...

Next.js production build encountering an infinite loading error

I have been utilizing the Next.js TypeScript starter from https://github.com/jpedroschmitz/typescript-nextjs-starter for my current project. The issue I am facing is that when I attempt to build the project after creating numerous components and files, it ...

Leverage Springs with TypeScript

function createDefaultOrder(items: any[]): number[] { return items.map((_, index) => index); } type CustomHandler<T> = (index: number) => T; type CustomValues = { zIndex: number, y: number, scale: number, shadow: number, immediate: ...

Dependency Injection: The constructor of the injectable class is called multiple times

There are multiple classes that inject the TermsExchangeService: import {TermsExchangeService} from './terms-exchange.service'; @injectable() export class TermsExchangeComponent { constructor( private termsExchangeService: TermsExchan ...

Verifying the presence of an object in an array based on its value using TypeScript

Having the following dataset: roles = [ {roleId: "69801", role: "ADMIN"} {roleId: "69806", role: "SUPER_ADMIN"} {roleId: "69805", role: "RB"} {roleId: "69804", role: "PILOTE"} {roleId: "69808", role: "VENDEUR"} {roleId: "69807", role: "SUPER_RB"} ] The o ...

custom field component for react-hook-form

I have been working on creating a form field component that can be utilized at both the root form level and as a nested field. export type FirstNameField = { firstName: string; }; type GenericFormType<T, NS extends string | never = never> = NS ext ...

The Angular Progressive Web App functions properly in ng serve mode, but encounters issues when running with http-server

I'm developing a Progressive Web App (PWA) using Angular. Everything was functioning smoothly until out of nowhere, I started encountering a 404 Error whenever I tried to navigate to a new component while serving in dist/project with http-server. Surp ...

Ngrx/effects will be triggered once all actions have been completed

I've implemented an effect that performs actions by iterating through an array: @Effect() changeId$ = this.actions$.pipe( ofType(ActionTypes.ChangeId), withLatestFrom(this.store.select(fromReducers.getAliasesNames)), switchMap(([action, aliases ...