#10

Subscribe to Action Results in NGRX with Facade Pattern

2019-08-20

TAGS: angularngrx

At work we recently moved our state management to ngrx with a Facade pattern.

The developer who selected and implemented our facade pattern told us that it was impossible to know whether a call was successful or not. With a new hire at work and some Googling, we found a solution that works for the short term.

This response on Stack Overflow worked for the most part, but seemed to be using a different version of ngrx. Putting the methods inside a pipe made it work:

[...]
import { Actions } from '@ngrx/effects';
[...]

@Component(...)
class SomeComponent implements OnDestroy {
    destroyed$ = new Subject<boolean>();

    constructor(updates$: Actions) {
        updates$
+            .pipe(
+            ofType(PostActions.SAVE_POST_SUCCESS),
+            takeUntil(this.destroyed$),
+            tap((arg) => console.log(arg))
+            ).subscribe();
-            .ofType(PostActions.SAVE_POST_SUCCESS)
-            .takeUntil(this.destroyed$)
-            .do(() => /* hooray, success, show notification alert ect.. */)
-            .subscribe();
    }

    ngOnDestroy() {
        this.destroyed$.next(true);
        this.destroyed$.complete();
    }
}

We'll eventually abstract this away into a class that our components can extend, but this is great for now.