Home > Enterprise >  Angular ng rx store get saved Object from map() and use it in tap() inside Effect
Angular ng rx store get saved Object from map() and use it in tap() inside Effect

Time:06-14

im working in angular 13 project im using ngrx store and it works fine. my issue is that i want to get the if from my saved object and show it in the toastr after save succes.

this is my effect code :

saveDemandeEffect: Observable<DemandeActions> = createEffect(

    () => this.effectActions.pipe(


        ofType(EnvelopeActionsTypes.SAVE_ENVELOPE),

        mergeMap((action: DemandeActions) => {

            return this.demandeService.saveDemande(action.payload)
                .pipe(
                    map((demande) => {
                        return new SaveDemandeActionSuccess(demande);
                    }),
                    tap(
                        () => {
                            // here i want to get saved demande object then demande.id to show it in the toastr msg bellow
                            this.toastr.success("message", "Confirmation")
                            this.router.navigate(['/envelopes']);
                        }
                    ),
                    catchError((err) => of(new SaveDemandeActionError(err.message)))
                )
        })
    )

);

do you have any idea how i can acheive this.

Thanks in advance

CodePudding user response:

Does this work for you? If you API on save returns the demande object, then you can take the required action in the map function itself


saveDemandeEffect: Observable<DemandeActions> = createEffect(

    () => this.effectActions.pipe(


        ofType(EnvelopeActionsTypes.SAVE_ENVELOPE),

        mergeMap((action: DemandeActions) => {

            return this.demandeService.saveDemande(action.payload)
                .pipe(
                    map((demande) => {
                        // you can get your demande id here ?
                        this.toastr.success("message", "Confirmation")
                        this.router.navigate(['/envelopes']);
                        return new SaveDemandeActionSuccess(demande);
                    }),
                    catchError((err) => of(new SaveDemandeActionError(err.message)))
                )
        })
    )

);

CodePudding user response:

Try by removing the nested pipes and use switchMap instead mergeMap.

    saveDemandeEffect: Observable<DemandeActions> = createEffect(
        () => this.effectActions.pipe(
            ofType(EnvelopeActionsTypes.SAVE_ENVELOPE),    
            switchMap((action: DemandeActions) => this.demandeService.saveDemande(action.payload)),
            map((demande) =>new SaveDemandeActionSuccess(demande)),
            tap(()=> {
               this.toastr.success("message", "Confirmation")
               this.router.navigate(['/envelopes']);
            }),
           catchError((err) => of(new SaveDemandeActionError(err.message))
        );
  • Related