1
1
import { Component , OnInit } from "@angular/core" ;
2
2
import { Store } from "@ngrx/store" ;
3
- import { State } from "src/app/shared/state " ;
3
+ import { Observable } from "rxjs " ;
4
4
import {
5
- BookModel ,
6
- calculateBooksGrossEarnings ,
7
- BookRequiredProps
8
- } from "src/app/shared/models/book.model" ;
5
+ State ,
6
+ selectAllBooks ,
7
+ selectActiveBook ,
8
+ selectBooksEarningsTotals
9
+ } from "src/app/shared/state" ;
10
+ import { BookModel , BookRequiredProps } from "src/app/shared/models/book.model" ;
9
11
import { BooksService } from "src/app/shared/services/book.service" ;
10
12
import { BooksPageActions , BooksApiActions } from "../../actions" ;
11
13
@@ -15,39 +17,30 @@ import { BooksPageActions, BooksApiActions } from "../../actions";
15
17
styleUrls : [ "./books-page.component.css" ]
16
18
} )
17
19
export class BooksPageComponent implements OnInit {
18
- books : BookModel [ ] = [ ] ;
19
- currentBook : BookModel | null = null ;
20
- total : number = 0 ;
21
-
22
- constructor (
23
- private booksService : BooksService ,
24
- private store : Store < State >
25
- ) { }
20
+ books$ : Observable < BookModel [ ] > ;
21
+ currentBook$ : Observable < BookModel | null > ;
22
+ total$ : Observable < number > ;
23
+
24
+ constructor ( private booksService : BooksService , private store : Store < State > ) {
25
+ this . books$ = store . select ( selectAllBooks ) ;
26
+ this . currentBook$ = store . select ( selectActiveBook ) ;
27
+ this . total$ = store . select ( selectBooksEarningsTotals ) ;
28
+ }
26
29
27
30
ngOnInit ( ) {
28
31
this . store . dispatch ( BooksPageActions . enter ( ) ) ;
29
32
30
33
this . getBooks ( ) ;
31
- this . removeSelectedBook ( ) ;
32
34
}
33
35
34
36
getBooks ( ) {
35
37
this . booksService . all ( ) . subscribe ( books => {
36
- this . books = books ;
37
- this . updateTotals ( books ) ;
38
-
39
38
this . store . dispatch ( BooksApiActions . booksLoaded ( { books } ) ) ;
40
39
} ) ;
41
40
}
42
41
43
- updateTotals ( books : BookModel [ ] ) {
44
- this . total = calculateBooksGrossEarnings ( books ) ;
45
- }
46
-
47
42
onSelect ( book : BookModel ) {
48
43
this . store . dispatch ( BooksPageActions . selectBook ( { bookId : book . id } ) ) ;
49
-
50
- this . currentBook = book ;
51
44
}
52
45
53
46
onCancel ( ) {
@@ -56,8 +49,6 @@ export class BooksPageComponent implements OnInit {
56
49
57
50
removeSelectedBook ( ) {
58
51
this . store . dispatch ( BooksPageActions . clearSelectedBook ( ) ) ;
59
-
60
- this . currentBook = null ;
61
52
}
62
53
63
54
onSave ( book : BookRequiredProps | BookModel ) {
@@ -85,9 +76,6 @@ export class BooksPageComponent implements OnInit {
85
76
) ;
86
77
87
78
this . booksService . update ( book . id , book ) . subscribe ( book => {
88
- this . getBooks ( ) ;
89
- this . removeSelectedBook ( ) ;
90
-
91
79
this . store . dispatch ( BooksApiActions . bookUpdated ( { book } ) ) ;
92
80
} ) ;
93
81
}
0 commit comments