|
1 | | -import { computed, effect } from '@angular/core'; |
| 1 | +import { computed, effect, inject } from '@angular/core'; |
2 | 2 | import { |
3 | 3 | patchState, |
4 | 4 | signalStore, |
|
7 | 7 | withMethods, |
8 | 8 | withState, |
9 | 9 | } from '@ngrx/signals'; |
| 10 | +import { EMPTY, Subject, catchError, mergeMap, tap } from 'rxjs'; |
10 | 11 | import { Photo } from '../photo.model'; |
| 12 | +import { PhotoService } from '../photos.service'; |
11 | 13 |
|
12 | 14 | export interface PhotoState { |
13 | 15 | photos: Photo[]; |
@@ -60,9 +62,55 @@ export const PhotoSignalStore = signalStore( |
60 | 62 | search: JSON.parse(savedJSONState).search, |
61 | 63 | page: JSON.parse(savedJSONState).page, |
62 | 64 | }); |
63 | | - effect(() => { |
64 | | - console.log('search/page', store.search(), store.page()); |
| 65 | + const photoService = inject(PhotoService); |
| 66 | + const querySearch = computed<{ search: string; page: number }>(() => ({ |
| 67 | + search: store.search(), |
| 68 | + page: store.page(), |
| 69 | + })); |
| 70 | + const querySearchSubject$ = new Subject<{ |
| 71 | + search: string; |
| 72 | + page: number; |
| 73 | + }>(); |
| 74 | + |
| 75 | + const sub = querySearchSubject$ |
| 76 | + .pipe( |
| 77 | + tap(() => patchState(store, { loading: true, error: '' })), |
| 78 | + mergeMap(({ search, page }) => { |
| 79 | + if (!search) { |
| 80 | + patchState(store, { |
| 81 | + photos: [], |
| 82 | + pages: 1, |
| 83 | + loading: false, |
| 84 | + }); |
| 85 | + return EMPTY; |
| 86 | + } |
| 87 | + return photoService.searchPublicPhotos(search, page).pipe( |
| 88 | + catchError((error) => { |
| 89 | + patchState(store, { loading: false, error: 'error' }); |
| 90 | + return EMPTY; |
| 91 | + }), |
| 92 | + ); |
| 93 | + }), |
| 94 | + ) |
| 95 | + .subscribe(({ photos }) => { |
| 96 | + patchState(store, { |
| 97 | + pages: photos.pages, |
| 98 | + photos: photos.photo, |
| 99 | + loading: false, |
| 100 | + }); |
| 101 | + localStorage.setItem( |
| 102 | + PHOTO_STATE_KEY, |
| 103 | + JSON.stringify({ search: store.search(), page: store.page() }), |
| 104 | + ); |
| 105 | + }); |
| 106 | + |
| 107 | + const ref = effect(() => querySearchSubject$.next(querySearch()), { |
| 108 | + allowSignalWrites: true, |
65 | 109 | }); |
| 110 | + return () => { |
| 111 | + ref.destroy(); |
| 112 | + sub.unsubscribe(); |
| 113 | + }; |
66 | 114 | }, |
67 | 115 | }), |
68 | 116 | ); |
0 commit comments