feat: Implement tasks feature using NGRX signals and remove the old counter store, alongside general project configuration and skill documentation updates.
continuous-integration/drone/pr Build is passing

This commit is contained in:
Dennis Hundertmark
2026-03-08 09:50:17 +01:00
parent 2184971175
commit 9d13cc652a
47 changed files with 15272 additions and 14144 deletions
+60 -54
View File
@@ -11,38 +11,46 @@ Configure routing in Angular v20+ with lazy loading, functional guards, and sign
```typescript
// app.routes.ts
import { Routes } from "@angular/router";
import { Routes } from '@angular/router';
export const routes: Routes = [
{ path: "", redirectTo: "/home", pathMatch: "full" },
{ path: "home", component: Home },
{ path: "about", component: About },
{ path: "**", component: NotFound },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: Home },
{ path: 'about', component: About },
{ path: '**', component: NotFound },
];
// app.config.ts
import { ApplicationConfig } from "@angular/core";
import { provideRouter } from "@angular/router";
import { routes } from "./app.routes";
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes)],
providers: [provideRouter(routes)],
};
// app.component.ts
import { Component } from "@angular/core";
import { RouterOutlet, RouterLink, RouterLinkActive } from "@angular/router";
import { Component } from '@angular/core';
import { RouterOutlet, RouterLink, RouterLinkActive } from '@angular/router';
@Component({
selector: "app-root",
imports: [RouterOutlet, RouterLink, RouterLinkActive],
template: `
<nav>
<a routerLink="/home" routerLinkActive="active">Home</a>
<a routerLink="/about" routerLinkActive="active">About</a>
</nav>
<router-outlet />
`,
selector: 'app-root',
imports: [RouterOutlet, RouterLink, RouterLinkActive],
template: `
<nav>
<a
routerLink="/home"
routerLinkActive="active"
>Home</a
>
<a
routerLink="/about"
routerLinkActive="active"
>About</a
>
</nav>
<router-outlet />
`,
})
export class App {}
```
@@ -54,29 +62,27 @@ Load feature modules on demand:
```typescript
// app.routes.ts
export const routes: Routes = [
{ path: "", redirectTo: "/home", pathMatch: "full" },
{ path: "home", component: Home },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: Home },
// Lazy load entire feature
{
path: "admin",
loadChildren: () =>
import("./admin/admin.routes").then((m) => m.adminRoutes),
},
// Lazy load entire feature
{
path: 'admin',
loadChildren: () => import('./admin/admin.routes').then((m) => m.adminRoutes),
},
// Lazy load single component
{
path: "settings",
loadComponent: () =>
import("./settings/settings.component").then((m) => m.Settings),
},
// Lazy load single component
{
path: 'settings',
loadComponent: () => import('./settings/settings.component').then((m) => m.Settings),
},
];
// admin/admin.routes.ts
export const adminRoutes: Routes = [
{ path: "", component: AdminDashboard },
{ path: "users", component: AdminUsers },
{ path: "settings", component: AdminSettings },
{ path: '', component: AdminDashboard },
{ path: 'users', component: AdminUsers },
{ path: 'settings', component: AdminSettings },
];
```
@@ -110,10 +116,10 @@ Enable with `withComponentInputBinding()`:
```typescript
// app.config.ts
import { provideRouter, withComponentInputBinding } from "@angular/router";
import { provideRouter, withComponentInputBinding } from '@angular/router';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes, withComponentInputBinding())],
providers: [provideRouter(routes, withComponentInputBinding())],
};
```
@@ -282,25 +288,25 @@ export class UserDetail {
```typescript
// Parent route with children
export const routes: Routes = [
{
path: "products",
component: ProductsLayout,
children: [
{ path: "", component: ProductList },
{ path: ":id", component: ProductDetail },
{ path: ":id/edit", component: ProductEdit },
],
},
{
path: 'products',
component: ProductsLayout,
children: [
{ path: '', component: ProductList },
{ path: ':id', component: ProductDetail },
{ path: ':id/edit', component: ProductEdit },
],
},
];
// ProductsLayout
@Component({
imports: [RouterOutlet],
template: `
<h1>Products</h1>
<router-outlet />
<!-- Child routes render here -->
`,
imports: [RouterOutlet],
template: `
<h1>Products</h1>
<router-outlet />
<!-- Child routes render here -->
`,
})
export class ProductsLayout {}
```
@@ -52,9 +52,9 @@
```typescript
export const userTitleResolver: ResolveFn<string> = (route) => {
const userService = inject(User);
const id = route.paramMap.get("id")!;
return userService.getById(id).pipe(map((user) => `${user.name} - Profile`));
const userService = inject(User);
const id = route.paramMap.get('id')!;
return userService.getById(id).pipe(map((user) => `${user.name} - Profile`));
};
```
@@ -64,107 +64,110 @@ export const userTitleResolver: ResolveFn<string> = (route) => {
```typescript
// auth.service.ts
@Injectable({ providedIn: "root" })
@Injectable({ providedIn: 'root' })
export class Auth {
private _user = signal<User | null>(null);
private _token = signal<string | null>(null);
private _user = signal<User | null>(null);
private _token = signal<string | null>(null);
readonly user = this._user.asReadonly();
readonly isAuthenticated = computed(() => this._user() !== null);
readonly user = this._user.asReadonly();
readonly isAuthenticated = computed(() => this._user() !== null);
private router = inject(Router);
private http = inject(HttpClient);
private router = inject(Router);
private http = inject(HttpClient);
async login(credentials: Credentials): Promise<boolean> {
try {
const response = await firstValueFrom(
this.http.post<AuthResponse>("/api/login", credentials),
);
async login(credentials: Credentials): Promise<boolean> {
try {
const response = await firstValueFrom(this.http.post<AuthResponse>('/api/login', credentials));
this._token.set(response.token);
this._user.set(response.user);
localStorage.setItem("token", response.token);
this._token.set(response.token);
this._user.set(response.user);
localStorage.setItem('token', response.token);
return true;
} catch {
return false;
return true;
} catch {
return false;
}
}
}
logout(): void {
this._user.set(null);
this._token.set(null);
localStorage.removeItem("token");
this.router.navigate(["/login"]);
}
async checkAuth(): Promise<boolean> {
const token = localStorage.getItem("token");
if (!token) return false;
try {
const user = await firstValueFrom(this.http.get<User>("/api/me"));
this._user.set(user);
this._token.set(token);
return true;
} catch {
localStorage.removeItem("token");
return false;
logout(): void {
this._user.set(null);
this._token.set(null);
localStorage.removeItem('token');
this.router.navigate(['/login']);
}
async checkAuth(): Promise<boolean> {
const token = localStorage.getItem('token');
if (!token) return false;
try {
const user = await firstValueFrom(this.http.get<User>('/api/me'));
this._user.set(user);
this._token.set(token);
return true;
} catch {
localStorage.removeItem('token');
return false;
}
}
}
}
// auth.guard.ts
export const authGuard: CanActivateFn = async (route, state) => {
const authService = inject(Auth);
const router = inject(Router);
const authService = inject(Auth);
const router = inject(Router);
// Check if already authenticated
if (authService.isAuthenticated()) {
return true;
}
// Check if already authenticated
if (authService.isAuthenticated()) {
return true;
}
// Try to restore session
const isValid = await authService.checkAuth();
if (isValid) {
return true;
}
// Try to restore session
const isValid = await authService.checkAuth();
if (isValid) {
return true;
}
// Redirect to login
return router.createUrlTree(["/login"], {
queryParams: { returnUrl: state.url },
});
// Redirect to login
return router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url },
});
};
// login.component.ts
@Component({
template: `
<form (ngSubmit)="login()">
<input [(ngModel)]="email" name="email" />
<input [(ngModel)]="password" name="password" type="password" />
<button type="submit">Login</button>
</form>
`,
template: `
<form (ngSubmit)="login()">
<input
name="email"
[(ngModel)]="email" />
<input
name="password"
type="password"
[(ngModel)]="password" />
<button type="submit">Login</button>
</form>
`,
})
export class Login {
private authService = inject(Auth);
private router = inject(Router);
private route = inject(ActivatedRoute);
private authService = inject(Auth);
private router = inject(Router);
private route = inject(ActivatedRoute);
email = "";
password = "";
email = '';
password = '';
async login() {
const success = await this.authService.login({
email: this.email,
password: this.password,
});
async login() {
const success = await this.authService.login({
email: this.email,
password: this.password,
});
if (success) {
const returnUrl = this.route.snapshot.queryParams["returnUrl"] || "/";
this.router.navigateByUrl(returnUrl);
if (success) {
const returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
this.router.navigateByUrl(returnUrl);
}
}
}
}
```
@@ -172,85 +175,79 @@ export class Login {
```typescript
// breadcrumb.service.ts
@Injectable({ providedIn: "root" })
@Injectable({ providedIn: 'root' })
export class Breadcrumb {
private router = inject(Router);
private route = inject(ActivatedRoute);
private router = inject(Router);
private route = inject(ActivatedRoute);
breadcrumbs = toSignal(
this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.buildBreadcrumbs(this.route.root)),
),
{ initialValue: [] },
);
breadcrumbs = toSignal(
this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.buildBreadcrumbs(this.route.root)),
),
{ initialValue: [] },
);
private buildBreadcrumbs(
route: ActivatedRoute,
url: string = "",
breadcrumbs: Breadcrumb[] = [],
): Breadcrumb[] {
const children = route.children;
private buildBreadcrumbs(route: ActivatedRoute, url: string = '', breadcrumbs: Breadcrumb[] = []): Breadcrumb[] {
const children = route.children;
if (children.length === 0) {
return breadcrumbs;
if (children.length === 0) {
return breadcrumbs;
}
for (const child of children) {
const routeUrl = child.snapshot.url.map((segment) => segment.path).join('/');
if (routeUrl) {
url += `/${routeUrl}`;
}
const label = child.snapshot.data['breadcrumb'];
if (label) {
breadcrumbs.push({ label, url });
}
return this.buildBreadcrumbs(child, url, breadcrumbs);
}
return breadcrumbs;
}
for (const child of children) {
const routeUrl = child.snapshot.url
.map((segment) => segment.path)
.join("/");
if (routeUrl) {
url += `/${routeUrl}`;
}
const label = child.snapshot.data["breadcrumb"];
if (label) {
breadcrumbs.push({ label, url });
}
return this.buildBreadcrumbs(child, url, breadcrumbs);
}
return breadcrumbs;
}
}
// Route config with breadcrumb data
export const routes: Routes = [
{
path: "products",
data: { breadcrumb: "Products" },
children: [
{ path: "", component: ProductList },
{
path: ":id",
data: { breadcrumb: "Product Details" },
component: ProductDetail,
},
],
},
{
path: 'products',
data: { breadcrumb: 'Products' },
children: [
{ path: '', component: ProductList },
{
path: ':id',
data: { breadcrumb: 'Product Details' },
component: ProductDetail,
},
],
},
];
// breadcrumb.component.ts
@Component({
selector: "app-breadcrumb",
template: `
<nav aria-label="Breadcrumb">
<ol>
<li><a routerLink="/">Home</a></li>
@for (crumb of breadcrumbService.breadcrumbs(); track crumb.url) {
<li>
<a [routerLink]="crumb.url">{{ crumb.label }}</a>
</li>
}
</ol>
</nav>
`,
selector: 'app-breadcrumb',
template: `
<nav aria-label="Breadcrumb">
<ol>
<li><a routerLink="/">Home</a></li>
@for (crumb of breadcrumbService.breadcrumbs(); track crumb.url) {
<li>
<a [routerLink]="crumb.url">{{ crumb.label }}</a>
</li>
}
</ol>
</nav>
`,
})
export class BreadcrumbCmpt {
breadcrumbService = inject(Breadcrumb);
breadcrumbService = inject(Breadcrumb);
}
```
@@ -334,12 +331,7 @@ this.router.navigate([{ outlets: { modal: null } }]);
### Built-in Strategies
```typescript
import {
provideRouter,
withPreloading,
PreloadAllModules,
NoPreloading,
} from "@angular/router";
import { provideRouter, withPreloading, PreloadAllModules, NoPreloading } from '@angular/router';
// Preload all lazy modules
provideRouter(routes, withPreloading(PreloadAllModules));
@@ -377,26 +369,26 @@ provideRouter(routes, withPreloading(SelectivePreloadStrategy))
### Network-Aware Preloading
```typescript
@Injectable({ providedIn: "root" })
@Injectable({ providedIn: 'root' })
export class NetworkAwarePreloadStrategy implements PreloadingStrategy {
preload(route: Route, load: () => Observable<any>): Observable<any> {
// Check network conditions
const connection = (navigator as any).connection;
preload(route: Route, load: () => Observable<any>): Observable<any> {
// Check network conditions
const connection = (navigator as any).connection;
if (connection) {
// Don't preload on slow connections
if (connection.saveData || connection.effectiveType === '2g') {
return of(null);
}
}
// Preload if marked
if (route.data?.['preload']) {
return load();
}
if (connection) {
// Don't preload on slow connections
if (connection.saveData || connection.effectiveType === "2g") {
return of(null);
}
}
// Preload if marked
if (route.data?.["preload"]) {
return load();
}
return of(null);
}
}
```
@@ -405,44 +397,44 @@ export class NetworkAwarePreloadStrategy implements PreloadingStrategy {
```typescript
// app.routes.ts
export const routes: Routes = [
{ path: "home", component: Home, data: { animation: "HomePage" } },
{ path: "about", component: About, data: { animation: "AboutPage" } },
{ path: 'home', component: Home, data: { animation: 'HomePage' } },
{ path: 'about', component: About, data: { animation: 'AboutPage' } },
];
// app.component.ts
@Component({
imports: [RouterOutlet],
template: `
<div [@routeAnimations]="getRouteAnimationData()">
<router-outlet />
</div>
`,
animations: [
trigger("routeAnimations", [
transition("HomePage <=> AboutPage", [
style({ position: "relative" }),
query(":enter, :leave", [
style({
position: "absolute",
top: 0,
left: 0,
width: "100%",
}),
imports: [RouterOutlet],
template: `
<div [@routeAnimations]="getRouteAnimationData()">
<router-outlet />
</div>
`,
animations: [
trigger('routeAnimations', [
transition('HomePage <=> AboutPage', [
style({ position: 'relative' }),
query(':enter, :leave', [
style({
position: 'absolute',
top: 0,
left: 0,
width: '100%',
}),
]),
query(':enter', [style({ left: '-100%' })]),
query(':leave', animateChild()),
group([
query(':leave', [animate('300ms ease-out', style({ left: '100%' }))]),
query(':enter', [animate('300ms ease-out', style({ left: '0%' }))]),
]),
]),
]),
query(":enter", [style({ left: "-100%" })]),
query(":leave", animateChild()),
group([
query(":leave", [animate("300ms ease-out", style({ left: "100%" }))]),
query(":enter", [animate("300ms ease-out", style({ left: "0%" }))]),
]),
]),
]),
],
],
})
export class AppMain {
getRouteAnimationData() {
return this.route.firstChild?.snapshot.data["animation"];
}
getRouteAnimationData() {
return this.route.firstChild?.snapshot.data['animation'];
}
}
```
@@ -450,20 +442,16 @@ export class AppMain {
```typescript
// app.config.ts
import {
provideRouter,
withInMemoryScrolling,
withRouterConfig,
} from "@angular/router";
import { provideRouter, withInMemoryScrolling, withRouterConfig } from '@angular/router';
provideRouter(
routes,
withInMemoryScrolling({
scrollPositionRestoration: "enabled", // or 'top'
anchorScrolling: "enabled",
}),
withRouterConfig({
onSameUrlNavigation: "reload",
}),
routes,
withInMemoryScrolling({
scrollPositionRestoration: 'enabled', // or 'top'
anchorScrolling: 'enabled',
}),
withRouterConfig({
onSameUrlNavigation: 'reload',
}),
);
```