how to subscribe to action success callback using ngrx and effects

后端 未结 6 1487
慢半拍i
慢半拍i 2020-12-07 17:43

I\'m trying to do simple thing - after some entity saved (using http request) I want to navigate back to list route. The problem is : how to subscribe to success action (or

6条回答
  •  时光取名叫无心
    2020-12-07 18:34

    Sure. That's possible. Please consider this example of listening for a saved contact.

    export class PageContactComponent implements OnInit, OnDestroy {
    
      destroy$ = new Subject();
        
      constructor(private actionsListener$: ActionsSubject) {}
    
      ngOnInit() {
        this.actionsListener$
          .pipe(ofType(ContactActionTypes.SAVE_SUCCESS))
          .pipe(takeUntil(this.destroy$))
          .subscribe((data: any) => {
            // Do your stuff here
          });
      }
    
      ngOnDestroy() {
        this.destroy$.next();
        this.destroy$.complete();
      }
    }
    

    Here, I have created an ActionsSubject named actionsListener$. In this example I am listening to ContactActionTypes.SAVE_SUCCESS (an action that happens when a contact has been saved). Describe your code in the subscribe section and don't forget to destroy the subscription.

    Edit: And here is what the Action looks like:

    export enum ContactActionTypes {
      SAVE_SUCCESS = "[Contact] Save Success",
    }
    
    export class ActionContactSaveSuccess implements Action {
      readonly type = ContactActionTypes.SAVE_SUCCESS;
    
      constructor(readonly payload: { contact: any }) {}
    }
    
    export type ContactActions = ActionContactSaveSuccess;
    

提交回复
热议问题