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 #1282

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

@Component({
selector: 'app-photos',
imports: [
ReactiveFormsModule,
MatFormFieldModule,
MatProgressBarModule,
NgIf,
NgFor,
MatInputModule,
LetDirective,
RouterLinkWithHref,
],
template: `
@@ -35,84 +30,67 @@ 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]="store.page() === 1"
[class.bg-gray-400]="store.page() === 1"
class="rounded-md border p-3 text-xl"
(click)="store.previousPage()">
(click)="store.setPageRelative(-1)">
<
</button>
<button
[disabled]="vm.endOfPage"
[class.bg-gray-400]="vm.endOfPage"
[disabled]="store.endOfPage()"
[class.bg-gray-400]="store.endOfPage()"
class="rounded-md border p-3 text-xl"
(click)="store.nextPage()">
(click)="store.setPageRelative(1)">
>
</button>
Page :{{ vm.page }} / {{ vm.pages }}
Page : {{ store.page() }} / {{ store.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>

@if (store.loading()) {
<mat-progress-bar mode="query" class="mt-5" />
}
<ul class="flex flex-wrap gap-4">
@for (photo of store.photos(); track photo.id) {
<li>
<a routerLink="detail" [queryParams]="{ photo: encode(photo) }">
<img
src="{{ photo.url_q }}"
alt="{{ photo.title }}"
class="image" />
</a>
</li>
} @empty {
<div>No Photos found. Type a search word.</div>
}
</ul>
<ng-template #noPhoto>
<div>No Photos found. Type a search word.</div>
</ng-template>
<footer class="text-red-500">
{{ vm.error }}
</footer>
<footer class="text-red-500">{{ store.error() }}</footer>
</section>
</ng-container>
`,
providers: [provideComponentStore(PhotoStore)],
providers: [PhotoStore2],
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;
search = new FormControl();
export default class PhotosComponent {
protected readonly store = inject(PhotoStore2);
protected readonly search = new FormControl();

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

trackById(index: number, photo: Photo) {
return photo.id;
this.search.valueChanges
.pipe(debounceTime(300), distinctUntilChanged(), takeUntilDestroyed())
.subscribe((searchTerm) => {
this.store.setSearch(searchTerm);
});
}

encode(photo: Photo) {
encode(photo: Photo): string {
return encodeURIComponent(JSON.stringify(photo));
}
}
Original file line number Diff line number Diff line change
@@ -71,8 +71,8 @@ export class PhotoStore
const savedState = JSON.parse(savedJSONState);
this.setState({
...initialState,
search: savedState.search,
page: savedState.page,
search: savedState.search ?? '',
page: savedState.page ?? 1,
});
}
}
128 changes: 128 additions & 0 deletions apps/signal/30-interop-rxjs-signal/src/app/list/photos2.store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { computed, effect, inject } from '@angular/core';
import {
patchState,
signalStore,
signalStoreFeature,
withComputed,
withHooks,
withMethods,
withState,
} from '@ngrx/signals';
import { rxMethod } from '@ngrx/signals/rxjs-interop';
import { pipe } from 'rxjs';
import { switchMap } from 'rxjs/internal/operators/switchMap';
import { tap } from 'rxjs/internal/operators/tap';
import { Photo } from '../photo.model';
import { PhotoService } from '../photos.service';

const PHOTO_STATE_KEY = 'photo_search';

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

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

export const PhotoStore2 = signalStore(
{
providedIn: 'root',
},
withState<PhotoState>(initialState),
withLocalStorage(PHOTO_STATE_KEY),
withComputed((state) => ({
endOfPage: computed(() => state.page() === state.pages()),
})),
withMethods((state, photoService = inject(PhotoService)) => ({
setPageRelative(offset: number) {
const newPage = state.page() + offset;
if (newPage > 0 && newPage <= state.pages()) {
patchState(state, { page: newPage });
}
},
setPage(page: number) {
patchState(state, {
page,
});
},
setSearch(search: string) {
patchState(state, {
search,
page: 1,
});
},
loadByFilter: rxMethod<{ query: string; page?: number }>(
pipe(
tap(() => patchState(state, { loading: true })),
switchMap(({ query, page }) =>
photoService.searchPublicPhotos(query, page ?? state.page()),
),
tap({
next: (response) => {
patchState(state, {
photos: response.photos.photo,
pages: response.photos.pages,
loading: false,
});
},
error: (error: unknown) => {
patchState(state, {
error,
loading: false,
});
},
}),
),
),
})),
withHooks((store) => ({
onInit() {
store.loadByFilter({ query: store.search(), page: store.page() });

effect(() => {
const search = store.search();
const page = store.page();
store.loadByFilter({ query: search, page });
});
},
})),
);

export function withLocalStorage(key: string) {
return signalStoreFeature(
withHooks({
onInit(store: any) {
const savedJSONState = localStorage.getItem(PHOTO_STATE_KEY);

if (savedJSONState) {
const savedState = JSON.parse(savedJSONState);
patchState(store, {
...initialState,
search: savedState.search,
page: savedState.page,
});
}

effect(() => {
const toSave = {
search: store.search(),
page: store.page(),
};

localStorage.setItem(key, JSON.stringify(toSave));
});
},
}),
);
}
Loading