Skip to content

Answer:14 #1350

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

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
19 changes: 12 additions & 7 deletions apps/rxjs/11-high-order-operator-bug/src/app/app.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { inject, Injectable } from '@angular/core';
import { merge, Observable, of } from 'rxjs';
import { LocalDBService, TopicType } from './localDB.service';
import { forkJoin, map, Observable, of } from 'rxjs';
import { Info, LocalDBService, TopicType } from './localDB.service';

@Injectable({ providedIn: 'root' })
export class AppService {
Expand All @@ -9,11 +9,16 @@ export class AppService {
getAllInfo = this.dbService.infos;

deleteOldTopics(type: TopicType): Observable<boolean> {
const deleteTopics = (infoByType: Info[]) => {
const results$ = infoByType.map((t) =>
this.dbService.deleteOneTopic(t.id),
);
return forkJoin(results$).pipe(
map((results) => results.every((value) => value === true)),
);
};

const infoByType = this.dbService.searchByType(type);
return infoByType.length > 0
? infoByType
.map((t) => this.dbService.deleteOneTopic(t.id))
.reduce((acc, curr) => merge(acc, curr), of(true))
: of(true);
return infoByType.length > 0 ? deleteTopics(infoByType) : of(true);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { of } from 'rxjs';

export type TopicType = 'food' | 'book' | 'sport';

interface Info {
export interface Info {
id: number;
topic: TopicType;
}
Expand Down
9 changes: 9 additions & 0 deletions apps/rxjs/14-race-condition/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,15 @@
"coverage": true
}
}
},
"component-test": {
"executor": "@nx/cypress:cypress",
"options": {
"cypressConfig": "cypress.config.ts",
"testingType": "component",
"skipServe:": true,
"devServerTarget": "rxjs-race-condition:build"
}
}
}
}
26 changes: 3 additions & 23 deletions apps/rxjs/14-race-condition/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
import {
ChangeDetectionStrategy,
Component,
inject,
OnInit,
} from '@angular/core';
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { take } from 'rxjs';
import { TopicModalComponent } from './topic-dialog.component';
import { TopicService, TopicType } from './topic.service';

@Component({
standalone: true,
Expand All @@ -17,24 +10,11 @@ import { TopicService, TopicType } from './topic.service';
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent implements OnInit {
export class AppComponent {
title = 'rxjs-race-condition';
dialog = inject(MatDialog);
topicService = inject(TopicService);
topics: TopicType[] = [];

ngOnInit(): void {
this.topicService
.fakeGetHttpTopic()
.pipe(take(1))
.subscribe((topics) => (this.topics = topics));
}

openTopicModal() {
this.dialog.open(TopicModalComponent, {
data: {
topics: this.topics,
},
});
this.dialog.open(TopicModalComponent);
}
}
13 changes: 8 additions & 5 deletions apps/rxjs/14-race-condition/src/app/topic-dialog.component.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { NgFor } from '@angular/common';
import { AsyncPipe, NgFor } from '@angular/common';
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { MatDialogModule } from '@angular/material/dialog';
import { take } from 'rxjs';
import { TopicService } from './topic.service';

@Component({
template: `
<h1 mat-dialog-title>Show all Topics</h1>
<div mat-dialog-content>
<ul>
<li *ngFor="let topic of data.topics">
<li *ngFor="let topic of topics$ | async">
{{ topic }}
</li>
</ul>
Expand All @@ -17,9 +19,10 @@ import { MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
<button mat-button mat-dialog-close>Close</button>
</div>
`,
imports: [MatDialogModule, MatButtonModule, NgFor],
imports: [MatDialogModule, MatButtonModule, NgFor, AsyncPipe],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TopicModalComponent {
data = inject(MAT_DIALOG_DATA);
topicService = inject(TopicService);
topics$ = this.topicService.fakeGetHttpTopic().pipe(take(1));
}
11 changes: 9 additions & 2 deletions apps/rxjs/38-catch-error/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { HttpClient } from '@angular/common/http';
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { Subject, concatMap, map } from 'rxjs';
import { Subject, catchError, concatMap, map, of } from 'rxjs';

@Component({
imports: [CommonModule, FormsModule],
Expand Down Expand Up @@ -41,7 +41,14 @@ export class AppComponent implements OnInit {
.pipe(
map(() => this.input),
concatMap((value) =>
this.http.get(`https://jsonplaceholder.typicode.com/${value}/1`),
this.http.get(`https://jsonplaceholder.typicode.com/${value}/1`).pipe(
catchError((error) => {
console.error('Error occurred:', error);
return of(
'Could not fetch api, possible values are posts, comments, albums, photos, todos, users',
);
}),
),
),
takeUntilDestroyed(this.destroyRef),
)
Expand Down
14 changes: 11 additions & 3 deletions apps/rxjs/49-hold-to-save-button/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,32 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { HoldableDirective } from './holdable.directive';

@Component({
imports: [],
imports: [HoldableDirective],
selector: 'app-root',
template: `
<main class="flex h-screen items-center justify-center">
<div
class="flex w-full max-w-screen-sm flex-col items-center gap-y-8 p-4">
<button
[appHoldable]="HOLD_TIME"
(appHoldableTime)="progress.set($event)"
(appHoldableCompleted)="onSend()"
class="rounded bg-indigo-600 px-4 py-2 font-bold text-white transition-colors ease-in-out hover:bg-indigo-700">
Hold me
</button>

<progress [value]="20" [max]="100"></progress>
<progress [value]="progress()" [max]="HOLD_TIME"></progress>
</div>
</main>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
progress = signal(0);

readonly HOLD_TIME = 800;

onSend() {
console.log('Save it!');
}
Expand Down
51 changes: 51 additions & 0 deletions apps/rxjs/49-hold-to-save-button/src/app/holdable.directive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Directive, ElementRef, inject, input, output } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
animationFrameScheduler,
delay,
filter,
fromEvent,
interval,
map,
merge,
switchMap,
takeUntil,
tap,
} from 'rxjs';

@Directive({ selector: '[appHoldable]', standalone: true })
export class HoldableDirective {
appHoldable = input(1000); // in ms
appHoldableDelayAfterComplete = input(300); // in ms
appHoldableTime = output<number>();
appHoldableCompleted = output<void>();

#el = inject(ElementRef);

constructor() {
const on$ = fromEvent(this.#el.nativeElement, 'mousedown');

const off$ = merge(
fromEvent(this.#el.nativeElement, 'mouseup'),
fromEvent(this.#el.nativeElement, 'mouseleave'),
).pipe(tap(() => this.appHoldableTime.emit(0)));

on$
.pipe(
switchMap(() =>
interval(10, animationFrameScheduler).pipe(
map((timeInCs) => timeInCs * 10),
filter((timeInMs) => this.appHoldable() >= timeInMs),
tap((progress) => this.appHoldableTime.emit(progress)),
takeUntil(off$),
),
),
filter((time) => time === this.appHoldable()),
tap(() => this.appHoldableCompleted.emit()),
delay(this.appHoldableDelayAfterComplete()),
tap(() => this.appHoldableTime.emit(0)),
takeUntilDestroyed(),
)
.subscribe();
}
}
24 changes: 10 additions & 14 deletions apps/signal/43-signal-input/src/app/user.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { TitleCasePipe } from '@angular/common';
import {
ChangeDetectionStrategy,
Component,
Input,
OnChanges,
computed,
input,
numberAttribute,
} from '@angular/core';

type Category = 'Youth' | 'Junior' | 'Open' | 'Senior';
Expand All @@ -18,23 +19,18 @@ const ageToCategory = (age: number): Category => {
selector: 'app-user',
imports: [TitleCasePipe],
template: `
{{ fullName | titlecase }} plays tennis in the {{ category }} category!!
{{ fullName() | titlecase }} plays tennis in the {{ category() }} category!!
`,
host: {
class: 'text-xl text-green-800',
},
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UserComponent implements OnChanges {
@Input({ required: true }) name!: string;
@Input() lastName?: string;
@Input() age?: string;
export class UserComponent {
name = input.required<string>();
lastName = input<string>();
age = input(0, { transform: numberAttribute });

fullName = '';
category: Category = 'Junior';

ngOnChanges(): void {
this.fullName = `${this.name} ${this.lastName ?? ''}`;
this.category = ageToCategory(Number(this.age) ?? 0);
}
fullName = computed(() => `${this.name()} ${this.lastName() ?? ''}`);
category = computed<Category>(() => ageToCategory(this.age()));
}
15 changes: 11 additions & 4 deletions apps/signal/50-bug-in-effect/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,18 @@ export class AppComponent {
gpu = model(false);

constructor() {
/*
Explain for your junior team mate why this bug occurs ...
*/
effect(() => {
if (this.drive() || this.ram() || this.gpu()) {
if (this.drive()) {
alert('Price increased!');
}
});
effect(() => {
if (this.ram()) {
alert('Price increased!');
}
});
effect(() => {
if (this.gpu()) {
alert('Price increased!');
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
effect,
inject,
signal,
untracked,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { UserService } from './user.service';
Expand Down Expand Up @@ -38,7 +39,8 @@ export class ActionsComponent {

constructor() {
effect(() => {
this.userService.log(this.action() ?? 'No action selected');
const action = this.action() ?? 'No action selected';
untracked(() => this.userService.log(action));
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import { UserStore } from './user.service';
template: `
<div cd-flash class="m-4 block border border-gray-500 p-4">
Address:
<div>Street: {{ userService.user().address.street }}</div>
<div>ZipCode: {{ userService.user().address.zipCode }}</div>
<div>City: {{ userService.user().address.city }}</div>
<div>Street: {{ userService.address.street() }}</div>
<div>ZipCode: {{ userService.address.zipCode() }}</div>
<div>City: {{ userService.address.city() }}</div>
</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import { UserStore } from './user.service';
template: `
<div cd-flash class="m-4 block border border-gray-500 p-4">
Job:
<div>title: {{ userService.user().title }}</div>
<div>salary: {{ userService.user().salary }}</div>
<div>title: {{ userService.title() }}</div>
<div>salary: {{ userService.salary() }}</div>
</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { UserStore } from './user.service';
selector: 'name',
template: `
<div cd-flash class="m-4 block border border-gray-500 p-4">
Name: {{ userService.user().name }}
Name: {{ userService.name() }}
</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { UserStore } from './user.service';
selector: 'note',
template: `
<div cd-flash class="m-4 block border border-gray-500 p-4">
Note: {{ userService.user().note }}
Note: {{ userService.note() }}
</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
Expand Down
Loading