Created
June 13, 2022 01:25
-
-
Save thecodinganalyst/75f39b8a9808dfb86eb9758fe0542a42 to your computer and use it in GitHub Desktop.
NgRx Effects Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Injectable() | |
export class BooksEffects { | |
loadBooks$ = createEffect(() => this.actions$.pipe( | |
ofType(BookStoreActions.loadBooks), | |
mergeMap(() => this.booksService.getBooks().pipe( | |
map(books => BookStoreActions.booksLoaded({books})), | |
catchError(() => EMPTY) | |
)) | |
)); | |
saveBook$ = createEffect(() => this.actions$.pipe( | |
ofType(BookStoreActions.saveBook), | |
mergeMap((action) => this.booksService.saveBook(action.book).pipe( | |
map(book => BookStoreActions.bookSaved({book})), | |
catchError(() => EMPTY) | |
)) | |
)); | |
bookSaved$ = createEffect(() => this.actions$.pipe( | |
ofType(BookStoreActions.bookSaved), | |
map(() => BookStoreActions.loadBooks()) | |
)); | |
deleteBook$ = createEffect(() => this.actions$.pipe( | |
ofType(BookStoreActions.deleteBook), | |
mergeMap((action) => this.booksService.deleteBook(action.id).pipe( | |
map(book => BookStoreActions.bookDeleted({book})), | |
catchError(() => EMPTY) | |
)) | |
)); | |
bookDeleted$ = createEffect(() => this.actions$.pipe( | |
ofType(BookStoreActions.bookDeleted), | |
map(() => BookStoreActions.loadBooks()) | |
)); | |
constructor (private actions$: Actions, private booksService: BooksService){} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment