Reputation: 3821
I am new to the ngrx state management and I'm using @ngrx/store and effect of 6.0.1, suppose I would like to save a new member contact so I have following prepared:
member.effect.ts
@Effect()
memberContactCreate$ = this.actions$.pipe(
ofType(MemberActions.MemberActionTypes.MemberContactCreate),
switchMap((action: MemberActions.MemberContactCreate) => {
return this.memberService.createMemberDetail(action.payload);
}),
map(
(response) => {
console.log('MemberContactCreate$ MemberContactCreate response: ', response);
if (!response.didError) {
return new MemberActions.MemberContactCreateSuccess(response.model as MemberDetailResponse);
} else {
return new MemberActions.MemberContactCreateFailure(response.errorMessage);
}
},
),
);
in my member contact component submit I will dispatch the create action
this.store.dispatch(new fromAction.MemberContactCreate(<MemberDetailRequest>this.memberDetailForm.value));
However, I would like to display a toastr or notification that if my member successfully created from server, which is defined in my @Effect method, return the new action "MemberActions.MemberContactCreateSuccess", but how could I catch this action in my component as soon as it gets fired? I tried to do something like below and put it in my ngOnInit and thought it could be used like a subscription but it's not, in fact it fires everytime like page load or even I did not dispatch my memberContactCreate action...
this.store.select(fromSelector.getMemberCreateSuccess)
.subscribe((stateSelector) => {
console.log('getMemberCreateSuccess: ', stateSelector);
setTimeout(() => {
this.toastr('Hooray',
'New contact has been created successfully!');
}, 800);
this.tableData = stateSelector;
});
So how could my component interact with my triggered ngrx action just like subject/subscription? I've been reading a lot materials online but most of the example stops at "CreateSuccessful" action which just pushed an item into stored object list, there is no continued UI interaction after that...**So how should the component receive or catch the **MemberContactCreateSuccess/Failure action and let user know your action is success or not?
Upvotes: 5
Views: 5560
Reputation: 15507
Personally I wouldn't handle the notifications within the component, but I would use @ngrx/effects to show/hide notifications. I briefly touch this in Start using ngrx/effects for this.
But if it's really necessary you can listen to your actions in your component just like you do in effects. You'll have to inject Actions
in your component, use the ofType
operator just like in the effects. The only difference is that you'll have to subscribe on the actions
observable within the component (in ngrx/effects this is done for you).
Upvotes: 6