diff --git a/src/app/books/books-api.effects.ts b/src/app/books/books-api.effects.ts index c762b77..da0adf3 100644 --- a/src/app/books/books-api.effects.ts +++ b/src/app/books/books-api.effects.ts @@ -1,5 +1,21 @@ import { Injectable } from "@angular/core"; import { createEffect, Actions, ofType } from "@ngrx/effects"; -import {} from "rxjs/operators"; +import { mergeMap, map } from "rxjs/operators"; import { BooksService } from "../shared/services"; import { BooksPageActions, BooksApiActions } from "./actions"; + +@Injectable() +export class BooksApiEffects { + constructor(private booksService: BooksService, private actions$: Actions) {} + + loadBooks$ = createEffect(() => + this.actions$.pipe( + ofType(BooksPageActions.enter), + mergeMap(() => + this.booksService + .all() + .pipe(map(books => BooksApiActions.booksLoaded({ books }))) + ) + ) + ); +} diff --git a/src/app/books/books.module.ts b/src/app/books/books.module.ts index 120ceb3..ac8dd1d 100644 --- a/src/app/books/books.module.ts +++ b/src/app/books/books.module.ts @@ -8,13 +8,15 @@ import { BooksPageComponent } from "./components/books-page/books-page.component import { BookDetailComponent } from "./components/book-detail/book-detail.component"; import { BooksListComponent } from "./components/books-list/books-list.component"; import { BooksTotalComponent } from "./components/books-total/books-total.component"; +import { BooksApiEffects } from "./books-api.effects"; @NgModule({ imports: [ CommonModule, ReactiveFormsModule, MaterialModule, - RouterModule.forChild([{ path: "books", component: BooksPageComponent }]) + RouterModule.forChild([{ path: "books", component: BooksPageComponent }]), + EffectsModule.forFeature([BooksApiEffects]) ], declarations: [ BooksPageComponent, diff --git a/src/app/books/components/books-page/books-page.component.ts b/src/app/books/components/books-page/books-page.component.ts index 683a762..4a4cb99 100755 --- a/src/app/books/components/books-page/books-page.component.ts +++ b/src/app/books/components/books-page/books-page.component.ts @@ -29,14 +29,6 @@ export class BooksPageComponent implements OnInit { ngOnInit() { this.store.dispatch(BooksPageActions.enter()); - - this.getBooks(); - } - - getBooks() { - this.booksService.all().subscribe(books => { - this.store.dispatch(BooksApiActions.booksLoaded({ books })); - }); } onSelect(book: BookModel) { @@ -63,7 +55,6 @@ export class BooksPageComponent implements OnInit { this.store.dispatch(BooksPageActions.createBook({ book: bookProps })); this.booksService.create(bookProps).subscribe(book => { - this.getBooks(); this.removeSelectedBook(); this.store.dispatch(BooksApiActions.bookCreated({ book })); @@ -84,7 +75,6 @@ export class BooksPageComponent implements OnInit { this.store.dispatch(BooksPageActions.deleteBook({ bookId: book.id })); this.booksService.delete(book.id).subscribe(() => { - this.getBooks(); this.removeSelectedBook(); this.store.dispatch(BooksApiActions.bookDeleted({ bookId: book.id }));