There is a common use case of wanting to perform some task inside a component based on actions that have been dispatched outside the component, normally with Effects. There are some common patterns to achieve this:
Use the Effects APIs to listen to dispatched actions:
import { Actions, ofType } from '@ngrx/effects';
@Component({ ... })
export class ActiveComponent {
destroy$ = new Subject();
constructor(private actions$: Actions) {}
ngOnInit() {
this.actions$.pipe(
ofType(someSuccessAction),
takeUntil(this.destroy$),
tap(() => {
this.doSomethingLocally();
})
).subscribe();
}
ngOnDestroy() {
this.destroy$.next();
}
doSomethingLocally() {
}
}
Set some property in your state slice that gets updated, and listen for when that piece of state is updated.
import { Actions, ofType } from '@ngrx/effects';
@Component({ ... })
export class ActiveComponent {
destroy$ = new Subject();
done$ = this.store.select(selectDoneFromStateSlice);
constructor(private store: Store<{}>) {}
ngOnInit() {
this.done$.pipe(
filter(done => !!done),
takeUntil(this.destroy$),
tap(() => {
this.doSomethingLocally();
})
).subscribe();
}
ngOnDestroy() {
this.destroy$.next();
}
doSomethingLocally() {
}
}
We should document a recommended way to do this for developers.
@brandonroberts Where should the documentation go?
Should this type of doc go under the Recipes section? As someone who has come from outside of the project when I first went to the docs and saw the Recipes section I was hoping to see some examples/docs on some common patterns I may need to follow when using NgRx.
This seems like a great example of what could go in this section of the docs.
@jordanpowell88 @Stephenradams yep, that seems like a good place to me.
This is exactly what I was looking for, thanks!
Most helpful comment
Should this type of doc go under the Recipes section? As someone who has come from outside of the project when I first went to the docs and saw the Recipes section I was hoping to see some examples/docs on some common patterns I may need to follow when using NgRx.
This seems like a great example of what could go in this section of the docs.