Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 116 additions & 0 deletions apps/angular/interop-rxjs-signal/src/app/list/photo-signal.store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { computed, effect, inject } from '@angular/core';
import {
patchState,
signalStore,
withComputed,
withHooks,
withMethods,
withState,
} from '@ngrx/signals';
import { EMPTY, Subject, catchError, mergeMap, tap } from 'rxjs';
import { Photo } from '../photo.model';
import { PhotoService } from '../photos.service';

export interface PhotoState {
photos: Photo[];
search: string;
page: number;
pages: number;
loading: boolean;
error: unknown;
}

const initialState: PhotoState = {
photos: [],
search: '',
page: 1,
pages: 1,
loading: false,
error: '',
};

const PHOTO_STATE_KEY = 'photo_search';

export const PhotoSignalStore = signalStore(
withState(initialState),
withComputed((store) => ({
endOfPage: computed(() => store.page() === store.pages()),
})),
withMethods((store) => {
return {
nextPage() {
patchState(store, {
page: store.page() + 1,
});
},
previousPage() {
patchState(store, {
page: store.page() - 1,
});
},
setSearch(search: string) {
patchState(store, { search, page: 1 });
},
};
}),
withHooks({
onInit(store) {
const savedJSONState = localStorage.getItem(PHOTO_STATE_KEY);
savedJSONState === null
? patchState(store)
: patchState(store, {
search: JSON.parse(savedJSONState).search,
page: JSON.parse(savedJSONState).page,
});
const photoService = inject(PhotoService);
const querySearch = computed<{ search: string; page: number }>(() => ({
search: store.search(),
page: store.page(),
}));
const querySearchSubject$ = new Subject<{
search: string;
page: number;
}>();

const sub = querySearchSubject$
.pipe(
tap(() => patchState(store, { loading: true, error: '' })),
mergeMap(({ search, page }) => {
if (!search) {
patchState(store, {
photos: [],
pages: 1,
loading: false,
});
return EMPTY;
}
return photoService.searchPublicPhotos(search, page).pipe(
catchError((error) => {
patchState(store, { loading: false, error: 'error' });
return EMPTY;
}),
);
}),
)
.subscribe(({ photos }) => {
patchState(store, {
pages: photos.pages,
photos: photos.photo,
loading: false,
});
localStorage.setItem(
PHOTO_STATE_KEY,
JSON.stringify({ search: store.search(), page: store.page() }),
);
});

const ref = effect(() => querySearchSubject$.next(querySearch()), {
allowSignalWrites: true,
});
return () => {
ref.destroy();
sub.unsubscribe();
};
},
}),
);
61 changes: 28 additions & 33 deletions apps/angular/interop-rxjs-signal/src/app/list/photos.component.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { NgFor, NgIf } from '@angular/common';
import { Component, OnInit, inject } from '@angular/core';
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { RouterLinkWithHref } from '@angular/router';
import { LetDirective } from '@ngrx/component';
import { provideComponentStore } from '@ngrx/component-store';
import { debounceTime, distinctUntilChanged, skipWhile, tap } from 'rxjs';
import { debounceTime, distinctUntilChanged, filter } from 'rxjs';
import { Photo } from '../photo.model';
import { PhotoSignalStore } from './photo-signal.store';
import { PhotoStore } from './photos.store';

@Component({
Expand All @@ -21,7 +22,6 @@ import { PhotoStore } from './photos.store';
NgIf,
NgFor,
MatInputModule,
LetDirective,
RouterLinkWithHref,
],
template: `
Expand All @@ -36,33 +36,36 @@ import { PhotoStore } from './photos.store';
placeholder="find a photo" />
</mat-form-field>

<ng-container *ngrxLet="vm$ as vm">
<ng-container>
<section class="flex flex-col">
<section class="flex items-center gap-3">
<button
[disabled]="vm.page === 1"
[class.bg-gray-400]="vm.page === 1"
[disabled]="signalStore.page() === 1"
[class.bg-gray-400]="signalStore.page() === 1"
class="rounded-md border p-3 text-xl"
(click)="store.previousPage()">
(click)="signalStore.previousPage()">
<
</button>
<button
[disabled]="vm.endOfPage"
[class.bg-gray-400]="vm.endOfPage"
[disabled]="signalStore.endOfPage()"
[class.bg-gray-400]="signalStore.endOfPage()"
class="rounded-md border p-3 text-xl"
(click)="store.nextPage()">
(click)="signalStore.nextPage()">
>
</button>
Page :{{ vm.page }} / {{ vm.pages }}
Page :{{ signalStore.page() }} / {{ signalStore.pages() }}
</section>
<mat-progress-bar
mode="query"
*ngIf="vm.loading"
*ngIf="signalStore.loading()"
class="mt-5"></mat-progress-bar>
<ul
class="flex flex-wrap gap-4"
*ngIf="vm.photos && vm.photos.length > 0; else noPhoto">
<li *ngFor="let photo of vm.photos; trackBy: trackById">
*ngIf="
signalStore.photos() && signalStore.photos().length > 0;
else noPhoto
">
<li *ngFor="let photo of signalStore.photos(); trackBy: trackById">
<a routerLink="detail" [queryParams]="{ photo: encode(photo) }">
<img
src="{{ photo.url_q }}"
Expand All @@ -75,38 +78,30 @@ import { PhotoStore } from './photos.store';
<div>No Photos found. Type a search word.</div>
</ng-template>
<footer class="text-red-500">
{{ vm.error }}
{{ signalStore.error() }}
</footer>
</section>
</ng-container>
`,
providers: [provideComponentStore(PhotoStore)],
providers: [provideComponentStore(PhotoStore), PhotoSignalStore],
host: {
class: 'p-5 block',
},
})
export default class PhotosComponent implements OnInit {
store = inject(PhotoStore);
readonly vm$ = this.store.vm$.pipe(
tap(({ search }) => {
if (!this.formInit) {
this.search.setValue(search);
this.formInit = true;
}
}),
);

private formInit = false;
readonly signalStore = inject(PhotoSignalStore);
private readonly destroyRef = inject(DestroyRef);
search = new FormControl();

ngOnInit(): void {
this.store.search(
this.search.valueChanges.pipe(
skipWhile(() => !this.formInit),
this.search.valueChanges
.pipe(
debounceTime(300),
distinctUntilChanged(),
),
);
filter((value) => value.length >= 3),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((searchValue) => this.signalStore.setSearch(searchValue));
}

trackById(index: number, photo: Photo) {
Expand Down
19 changes: 19 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"@ngrx/effects": "17.0.1",
"@ngrx/entity": "17.0.1",
"@ngrx/router-store": "17.0.1",
"@ngrx/signals": "^17.2.0",
"@ngrx/store": "17.0.1",
"@nx/angular": "17.2.8",
"@rx-angular/cdk": "^17.0.0",
Expand Down
Loading