Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Answer:30 #1111

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
87 changes: 42 additions & 45 deletions apps/signal/30-interop-rxjs-signal/src/app/list/photos.component.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import { NgFor, NgIf } from '@angular/common';
import { Component, 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, tap } from 'rxjs';
import { Photo } from '../photo.model';
import { PhotoStore } from './photos.store';

@Component({
selector: 'app-photos',
standalone: true,
Expand All @@ -36,7 +35,7 @@ import { PhotoStore } from './photos.store';
placeholder="find a photo" />
</mat-form-field>

<ng-container *ngrxLet="vm$ as vm">
@if (vm(); as vm) {
<section class="flex flex-col">
<section class="flex items-center gap-3">
<button
Expand All @@ -55,62 +54,60 @@ import { PhotoStore } from './photos.store';
</button>
Page :{{ vm.page }} / {{ vm.pages }}
</section>
<mat-progress-bar
mode="query"
*ngIf="vm.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">
<a routerLink="detail" [queryParams]="{ photo: encode(photo) }">
<img
src="{{ photo.url_q }}"
alt="{{ photo.title }}"
class="image" />
</a>
</li>
</ul>
<ng-template #noPhoto>
@if (vm.loading) {
<mat-progress-bar
mode="query"
*ngIf="vm.loading"
class="mt-5"></mat-progress-bar>
}

@if (vm.photos && vm.photos.length > 0) {
<ul class="flex flex-wrap gap-4">
@for (photo of vm.photos; track photo.id) {
<li>
<a routerLink="detail" [queryParams]="{ photo: encode(photo) }">
<img
src="{{ photo.url_q }}"
alt="{{ photo.title }}"
class="image" />
</a>
</li>
}
</ul>
} @else {
<div>No Photos found. Type a search word.</div>
</ng-template>
}
<footer class="text-red-500">
{{ vm.error }}
</footer>
</section>
</ng-container>
}
`,
providers: [provideComponentStore(PhotoStore)],
providers: [PhotoStore],
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;
}
}),
);
readonly vm = this.store.vm;
search = new FormControl(this.vm().search);

private formInit = false;
search = new FormControl();
private searchInput = this.search.valueChanges.pipe(
debounceTime(300),
distinctUntilChanged(),
takeUntilDestroyed(),
);

ngOnInit(): void {
this.store.search(
this.search.valueChanges.pipe(
skipWhile(() => !this.formInit),
debounceTime(300),
distinctUntilChanged(),
),
);
}

trackById(index: number, photo: Photo) {
return photo.id;
this.searchInput
.pipe(
filter((searchInputValue) => !!searchInputValue),
tap((searchInputValue) => {
this.store.search(searchInputValue!);
}),
)
.subscribe();
}

encode(photo: Photo) {
Expand Down
192 changes: 86 additions & 106 deletions apps/signal/30-interop-rxjs-signal/src/app/list/photos.store.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { Injectable, inject } from '@angular/core';
import { computed, inject } from '@angular/core';
import { tapResponse } from '@ngrx/operators';
import {
ComponentStore,
OnStateInit,
OnStoreInit,
tapResponse,
} from '@ngrx/component-store';
patchState,
signalStore,
withComputed,
withHooks,
withMethods,
withState,
} from '@ngrx/signals';
import { rxMethod } from '@ngrx/signals/rxjs-interop';
import { pipe } from 'rxjs';
import { filter, mergeMap, tap } from 'rxjs/operators';
import { Photo } from '../photo.model';
Expand All @@ -30,106 +34,82 @@ const initialState: PhotoState = {
error: '',
};

@Injectable()
export class PhotoStore
extends ComponentStore<PhotoState>
implements OnStoreInit, OnStateInit
{
private photoService = inject(PhotoService);

private readonly photos$ = this.select((s) => s.photos);
private readonly search$ = this.select((s) => s.search);
private readonly page$ = this.select((s) => s.page);
private readonly pages$ = this.select((s) => s.pages);
private readonly error$ = this.select((s) => s.error);
private readonly loading$ = this.select((s) => s.loading);

private readonly endOfPage$ = this.select(
this.page$,
this.pages$,
(page, pages) => page === pages,
);

readonly vm$ = this.select(
{
photos: this.photos$,
search: this.search$,
page: this.page$,
pages: this.pages$,
endOfPage: this.endOfPage$,
loading: this.loading$,
error: this.error$,
},
{ debounce: true },
);

ngrxOnStoreInit() {
const savedJSONState = localStorage.getItem(PHOTO_STATE_KEY);
if (savedJSONState === null) {
this.setState(initialState);
} else {
const savedState = JSON.parse(savedJSONState);
this.setState({
...initialState,
search: savedState.search,
page: savedState.page,
});
}
}

ngrxOnStateInit() {
this.searchPhotos(
this.select({
search: this.search$,
page: this.page$,
}),
);
}

readonly search = this.updater(
(state, search: string): PhotoState => ({
...state,
search,
page: 1,
}),
);

readonly nextPage = this.updater(
(state): PhotoState => ({
...state,
page: state.page + 1,
export const PhotoStore = signalStore(
withState(initialState),
withComputed(({ page, pages }) => ({
endOfPage: computed(() => page() === pages()),
})),
withComputed(
({ photos, search, page, pages, loading, error, endOfPage }) => ({
vm: computed(() => ({
photos: photos(),
search: search(),
page: page(),
pages: pages(),
loading: loading(),
error: error(),
endOfPage: endOfPage(),
})),
}),
);

readonly previousPage = this.updater(
(state): PhotoState => ({
...state,
page: state.page - 1,
}),
);

readonly searchPhotos = this.effect<{ search: string; page: number }>(
pipe(
filter(({ search }) => search.length >= 3),
tap(() => this.patchState({ loading: true, error: '' })),
mergeMap(({ search, page }) =>
this.photoService.searchPublicPhotos(search, page).pipe(
tapResponse(
({ photos: { photo, pages } }) => {
this.patchState({
loading: false,
photos: photo,
pages,
});
localStorage.setItem(
PHOTO_STATE_KEY,
JSON.stringify({ search, page }),
);
},
(error: unknown) => this.patchState({ error, loading: false }),
),
),
),
withHooks({
onInit(store) {
const savedJSONState = localStorage.getItem(PHOTO_STATE_KEY);
if (savedJSONState) {
const savedState = JSON.parse(savedJSONState);
patchState(store, () => {
return {
searchTerm: savedState.searchTerm,
page: savedState.page,
};
});
}
},
onDestroy() {
console.log('destroying store');
},
}),
withMethods((state, photoService = inject(PhotoService)) => ({
searchPhotos: rxMethod<void>(
pipe(
filter(() => state.search().length >= 3),
tap(() => patchState(state, { loading: true, error: '' })),
mergeMap(() => {
const searchTerm = state.search();
const page = state.page();
return photoService.searchPublicPhotos(searchTerm, page).pipe(
tapResponse({
next: ({ photos: { photo, pages } }) => {
patchState(state, {
loading: false,
pages,
photos: photo,
});
localStorage.setItem(
PHOTO_STATE_KEY,
JSON.stringify({ searchTerm, page }),
);
},
error: (error: unknown) =>
patchState(state, { error, loading: false }),
}),
);
}),
),
),
);
}
})),
withMethods((state) => ({
search(search: string) {
patchState(state, { search, page: 1 });
state.searchPhotos();
},
nextPage() {
patchState(state, { page: state.page() + 1 });
state.searchPhotos();
},
previousPage() {
patchState(state, { page: state.page() - 1 });
state.searchPhotos();
},
})),
);
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
"rxjs": "7.8.1",
"tailwindcss": "3.4.3",
"tslib": "^2.3.0",
"zone.js": "0.14.2"
"zone.js": "0.14.2",
"@ngrx/signals": "17.1.1"
},
"devDependencies": {
"@angular-devkit/build-angular": "18.1.1",
Expand Down
Loading