feat(doc): move notifivation

This commit is contained in:
thomas
2023-10-18 09:52:27 +02:00
parent 27e7137716
commit c0caace62f
32 changed files with 19 additions and 19 deletions

View File

@@ -0,0 +1,36 @@
{
"extends": ["../../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts"],
"extends": [
"plugin:@nx/angular",
"plugin:@angular-eslint/template/process-inline-templates"
],
"rules": {
"@angular-eslint/directive-selector": [
"error",
{
"type": "attribute",
"prefix": "app",
"style": "camelCase"
}
],
"@angular-eslint/component-selector": [
"error",
{
"type": "element",
"prefix": "app",
"style": "kebab-case"
}
]
}
},
{
"files": ["*.html"],
"extends": ["plugin:@nx/angular-template"],
"rules": {}
}
]
}

View File

@@ -0,0 +1,13 @@
# Power of Effect
> Author: Thomas Laforge
### Run Application
```bash
npx nx serve ngrx-notification
```
### Documentation and Instruction
Challenge documentation is [here](https://angular-challenges.vercel.app/challenges/ngrx/7-power-effect/).

View File

@@ -0,0 +1,88 @@
{
"name": "ngrx-notification",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"projectType": "application",
"sourceRoot": "apps/ngrx/notification/src",
"prefix": "app",
"targets": {
"build": {
"executor": "@angular-devkit/build-angular:browser",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/apps/ngrx/notification",
"index": "apps/ngrx/notification/src/index.html",
"main": "apps/ngrx/notification/src/main.ts",
"polyfills": "apps/ngrx/notification/src/polyfills.ts",
"tsConfig": "apps/ngrx/notification/tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"apps/ngrx/notification/src/favicon.ico",
"apps/ngrx/notification/src/assets"
],
"styles": ["apps/ngrx/notification/src/styles.scss"],
"scripts": [],
"allowedCommonJsDependencies": ["seedrandom"]
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"fileReplacements": [
{
"replace": "apps/ngrx/notification/src/environments/environment.ts",
"with": "apps/ngrx/notification/src/environments/environment.prod.ts"
}
],
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"executor": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "ngrx-notification:build:production"
},
"development": {
"browserTarget": "ngrx-notification:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"executor": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "ngrx-notification:build"
}
},
"lint": {
"executor": "@nx/linter:eslint",
"options": {
"lintFilePatterns": [
"apps/ngrx/notification/**/*.ts",
"apps/ngrx/notification/**/*.html"
]
}
}
},
"tags": []
}

View File

@@ -0,0 +1,8 @@
import { createActionGroup, emptyProps } from '@ngrx/store';
export const appActions = createActionGroup({
source: 'App Component',
events: {
'Init App': emptyProps(),
},
});

View File

@@ -0,0 +1,40 @@
import { Component, inject, OnInit } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';
import { Store } from '@ngrx/store';
import { appActions } from './app.actions';
@Component({
standalone: true,
imports: [RouterOutlet, RouterLink],
selector: 'app-root',
template: `
<nav>
<button routerLink="/teacher">Teacher</button>
<button routerLink="/student">Student</button>
<button routerLink="/school">School</button>
</nav>
<router-outlet></router-outlet>
`,
styles: [
`
:host {
display: flex;
flex-direction: column;
gap: 20px;
nav {
display: flex;
gap: 20px;
}
}
`,
],
})
export class AppComponent implements OnInit {
private store = inject(Store);
ngOnInit(): void {
this.store.dispatch(appActions.initApp());
}
}

View File

@@ -0,0 +1,47 @@
import { ApplicationConfig } from '@angular/core';
import { provideStore } from '@ngrx/store';
import { provideEffects } from '@ngrx/effects';
import { TeacherEffects } from './teacher/store/teacher.effects';
import { StudentEffects } from './student/store/student.effects';
import { provideRouter } from '@angular/router';
import { ROUTES } from './routes';
import { APP_INITIALIZER, inject } from '@angular/core';
import { FakeBackendService } from '@angular-challenges/ngrx-notification/backend';
import { NotificationService } from './data-access/notification.service';
import {
teacherReducer,
teachersFeatureKey,
} from './teacher/store/teacher.reducer';
import {
studentReducer,
studentsFeatureKey,
} from './student/store/student.reducer';
const REDUCERS = {
[teachersFeatureKey]: teacherReducer,
[studentsFeatureKey]: studentReducer,
};
export const appConfig: ApplicationConfig = {
providers: [
provideStore(REDUCERS),
provideEffects([TeacherEffects, StudentEffects]),
provideRouter(ROUTES),
{
provide: APP_INITIALIZER,
multi: true,
useFactory: () => {
const service = inject(FakeBackendService);
return () => service.start();
},
},
{
provide: APP_INITIALIZER,
multi: true,
useFactory: () => {
const service = inject(NotificationService);
return () => service.init();
},
},
],
};

View File

@@ -0,0 +1,14 @@
import { FakeBackendService } from '@angular-challenges/ngrx-notification/backend';
import { inject, Injectable } from '@angular/core';
import { take } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class HttpService {
private fakeBackend = inject(FakeBackendService);
getAllTeachers = () => this.fakeBackend.getAllTeachers().pipe(take(1));
getAllStudents = () => this.fakeBackend.getAllStudents().pipe(take(1));
getAllSchools = () => this.fakeBackend.getAllStchools().pipe(take(1));
}

View File

@@ -0,0 +1,40 @@
import { PushService } from '@angular-challenges/ngrx-notification/backend';
import {
isSchool,
isStudent,
isTeacher,
Push,
} from '@angular-challenges/ngrx-notification/model';
import { inject, Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import { filter } from 'rxjs';
import { studentActions } from '../student/store/student.actions';
import { teacherActions } from '../teacher/store/teacher.actions';
@Injectable({ providedIn: 'root' })
export class NotificationService {
private pushService = inject(PushService);
private store = inject(Store);
init() {
this.pushService.notification$
.pipe(filter(Boolean))
.subscribe((notification: Push) => {
if (isTeacher(notification)) {
this.store.dispatch(
teacherActions.addOneTeacher({ teacher: notification })
);
}
if (isStudent(notification)) {
this.store.dispatch(
studentActions.addOneStudent({ student: notification })
);
}
if (isSchool(notification)) {
// SchoolStore is not providedin root. thus at initialization, SchoolStore is undefined
// Option 1: set SchoolStore in root, but we don't want this to separate our class.
// Option 2: your turn
}
});
}
}

View File

@@ -0,0 +1,20 @@
import { Route } from '@angular/router';
export const ROUTES: Route[] = [
{ path: '', pathMatch: 'full', redirectTo: 'teacher' },
{
path: 'teacher',
loadComponent: () =>
import('./teacher/teacher.component').then((m) => m.TeacherComponent),
},
{
path: 'student',
loadComponent: () =>
import('./student/student.component').then((m) => m.StudentComponent),
},
{
path: 'school',
loadComponent: () =>
import('./school/school.component').then((m) => m.SchoolComponent),
},
];

View File

@@ -0,0 +1,33 @@
/* eslint-disable @angular-eslint/component-selector */
import { AsyncPipe, NgFor } from '@angular/common';
import { Component, inject } from '@angular/core';
import { provideComponentStore } from '@ngrx/component-store';
import { SchoolStore } from './school.store';
@Component({
standalone: true,
imports: [NgFor, AsyncPipe],
providers: [provideComponentStore(SchoolStore)],
selector: 'school',
template: `
<h3>SCHOOL</h3>
<div *ngFor="let school of school$ | async">
{{ school.name }} - {{ school.version }}
</div>
`,
styles: [
`
:host {
display: block;
width: fit-content;
height: fit-content;
border: 1px solid red;
padding: 4px;
}
`,
],
})
export class SchoolComponent {
private store = inject(SchoolStore);
school$ = this.store.schools$;
}

View File

@@ -0,0 +1,48 @@
import { School } from '@angular-challenges/ngrx-notification/model';
import { Injectable } from '@angular/core';
import {
ComponentStore,
OnStoreInit,
tapResponse,
} from '@ngrx/component-store';
import { pipe, switchMap } from 'rxjs';
import { HttpService } from '../data-access/http.service';
@Injectable()
export class SchoolStore
extends ComponentStore<{ schools: School[] }>
implements OnStoreInit
{
readonly schools$ = this.select((state) => state.schools);
constructor(private httpService: HttpService) {
super({ schools: [] });
}
addSchool = this.updater((state, school: School) => ({
...state,
schools: [...state.schools, school],
}));
updateSchool = this.updater((state, school: School) => ({
...state,
schools: state.schools.map((t) => (t.id === school.id ? school : t)),
}));
private readonly loadSchools = this.effect<void>(
pipe(
switchMap(() =>
this.httpService.getAllSchools().pipe(
tapResponse(
(schools) => this.patchState({ schools }),
(_) => _
)
)
)
)
);
ngrxOnStoreInit() {
this.loadSchools();
}
}

View File

@@ -0,0 +1,10 @@
import { Student } from '@angular-challenges/ngrx-notification/model';
import { createActionGroup, props } from '@ngrx/store';
export const studentActions = createActionGroup({
source: 'Student API',
events: {
'Add One Student': props<{ student: Student }>(),
'Add All Students': props<{ students: Student[] }>(),
},
});

View File

@@ -0,0 +1,23 @@
import { inject, Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { map, switchMap } from 'rxjs';
import { appActions } from '../../app.actions';
import { HttpService } from '../../data-access/http.service';
import { studentActions } from './student.actions';
@Injectable()
export class StudentEffects {
private actions$ = inject(Actions);
private httpService = inject(HttpService);
loadStudents$ = createEffect(() =>
this.actions$.pipe(
ofType(appActions.initApp),
switchMap(() =>
this.httpService
.getAllStudents()
.pipe(map((students) => studentActions.addAllStudents({ students })))
)
)
);
}

View File

@@ -0,0 +1,24 @@
import { Student } from '@angular-challenges/ngrx-notification/model';
import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity';
import { createReducer, on } from '@ngrx/store';
import { studentActions } from './student.actions';
export const studentsFeatureKey = 'students';
export type StudentState = EntityState<Student>;
export const studentAdapter: EntityAdapter<Student> =
createEntityAdapter<Student>();
export const studentReducer = createReducer(
studentAdapter.getInitialState(),
on(studentActions.addOneStudent, (state, { student }) =>
studentAdapter.upsertOne(student, state)
),
on(studentActions.addAllStudents, (state, { students }) =>
studentAdapter.setAll(students, state)
)
);
export const { selectIds, selectEntities, selectAll, selectTotal } =
studentAdapter.getSelectors();

View File

@@ -0,0 +1,17 @@
import { createFeatureSelector, createSelector } from '@ngrx/store';
import {
studentAdapter,
studentsFeatureKey,
StudentState,
} from './student.reducer';
const selectStudentState =
createFeatureSelector<StudentState>(studentsFeatureKey);
export const { selectAll } = studentAdapter.getSelectors();
const selectStudents = createSelector(selectStudentState, selectAll);
export const StudentSelectors = {
selectStudents,
};

View File

@@ -0,0 +1,32 @@
/* eslint-disable @angular-eslint/component-selector */
import { AsyncPipe, NgFor } from '@angular/common';
import { Component, inject } from '@angular/core';
import { Store } from '@ngrx/store';
import { StudentSelectors } from './store/student.selectors';
@Component({
standalone: true,
imports: [NgFor, AsyncPipe],
selector: 'student',
template: `
<h3>STUDENTS</h3>
<div *ngFor="let student of students$ | async">
{{ student.firstname }} {{ student.lastname }} - {{ student.version }}
</div>
`,
styles: [
`
:host {
display: block;
width: fit-content;
height: fit-content;
border: 1px solid red;
padding: 4px;
}
`,
],
})
export class StudentComponent {
private store = inject(Store);
students$ = this.store.select(StudentSelectors.selectStudents);
}

View File

@@ -0,0 +1,10 @@
import { Teacher } from '@angular-challenges/ngrx-notification/model';
import { createActionGroup, props } from '@ngrx/store';
export const teacherActions = createActionGroup({
source: 'Teacher API',
events: {
'Add One Teacher': props<{ teacher: Teacher }>(),
'Add All Teachers': props<{ teachers: Teacher[] }>(),
},
});

View File

@@ -0,0 +1,23 @@
import { inject, Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { map, switchMap } from 'rxjs';
import { appActions } from '../../app.actions';
import { HttpService } from '../../data-access/http.service';
import { teacherActions } from './teacher.actions';
@Injectable()
export class TeacherEffects {
private actions$ = inject(Actions);
private httpService = inject(HttpService);
loadTeachers$ = createEffect(() =>
this.actions$.pipe(
ofType(appActions.initApp),
switchMap(() =>
this.httpService
.getAllTeachers()
.pipe(map((teachers) => teacherActions.addAllTeachers({ teachers })))
)
)
);
}

View File

@@ -0,0 +1,24 @@
import { Teacher } from '@angular-challenges/ngrx-notification/model';
import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity';
import { createReducer, on } from '@ngrx/store';
import { teacherActions } from './teacher.actions';
export const teachersFeatureKey = 'teachers';
export type TeacherState = EntityState<Teacher>;
export const teacherAdapter: EntityAdapter<Teacher> =
createEntityAdapter<Teacher>();
export const teacherReducer = createReducer(
teacherAdapter.getInitialState(),
on(teacherActions.addOneTeacher, (state, { teacher }) =>
teacherAdapter.upsertOne(teacher, state)
),
on(teacherActions.addAllTeachers, (state, { teachers }) =>
teacherAdapter.setAll(teachers, state)
)
);
export const { selectIds, selectEntities, selectAll, selectTotal } =
teacherAdapter.getSelectors();

View File

@@ -0,0 +1,17 @@
import { createFeatureSelector, createSelector } from '@ngrx/store';
import {
teacherAdapter,
teachersFeatureKey,
TeacherState,
} from './teacher.reducer';
const selectTeacherState =
createFeatureSelector<TeacherState>(teachersFeatureKey);
export const { selectAll } = teacherAdapter.getSelectors();
const selectTeachers = createSelector(selectTeacherState, selectAll);
export const TeacherSelectors = {
selectTeachers,
};

View File

@@ -0,0 +1,33 @@
/* eslint-disable @angular-eslint/component-selector */
import { AsyncPipe, NgFor } from '@angular/common';
import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { TeacherSelectors } from './store/teacher.selectors';
@Component({
standalone: true,
imports: [NgFor, AsyncPipe],
selector: 'teacher',
template: `
<h3>TEACHERS</h3>
<div *ngFor="let teacher of teacher$ | async">
{{ teacher.firstname }} {{ teacher.lastname }} - {{ teacher.version }}
</div>
`,
styles: [
`
:host {
display: block;
width: fit-content;
height: fit-content;
border: 1px solid red;
padding: 4px;
}
`,
],
})
export class TeacherComponent {
teacher$ = this.store.select(TeacherSelectors.selectTeachers);
constructor(private store: Store) {}
}

View File

@@ -0,0 +1,3 @@
export const environment = {
production: true,
};

View File

@@ -0,0 +1,16 @@
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false,
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/plugins/zone-error'; // Included with Angular CLI.

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>NgrxNotification</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<app-root></app-root>
</body>
</html>

View File

@@ -0,0 +1,15 @@
import { appConfig } from './app/app.config';
import { bootstrapApplication } from '@angular/platform-browser';
import { enableProdMode } from '@angular/core';
import { AppComponent } from './app/app.component';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
bootstrapApplication(AppComponent, appConfig).catch((err) =>
console.error(err)
);

View File

@@ -0,0 +1,52 @@
/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes recent versions of Safari, Chrome (including
* Opera), Edge on the desktop, and iOS and Chrome on mobile.
*
* Learn more in https://angular.io/guide/browser-support
*/
/***************************************************************************************************
* BROWSER POLYFILLS
*/
/**
* By default, zone.js will patch all possible macroTask and DomEvents
* user can disable parts of macroTask/DomEvents patch by setting following flags
* because those flags need to be set before `zone.js` being loaded, and webpack
* will put import in the top of bundle, so user need to create a separate file
* in this directory (for example: zone-flags.ts), and put the following flags
* into that file, and then add the following code before importing zone.js.
* import './zone-flags';
*
* The flags allowed in zone-flags.ts are listed here.
*
* The following flags will work for all browsers.
*
* (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
* (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
* (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
*
* in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
* with the following flag, it will bypass `zone.js` patch for IE/Edge
*
* (window as any).__Zone_enable_cross_context_check = true;
*
*/
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js'; // Included with Angular CLI.
/***************************************************************************************************
* APPLICATION IMPORTS
*/

View File

@@ -0,0 +1 @@
/* You can add global styles to this file, and also import other style files */

View File

@@ -0,0 +1,12 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"types": [],
"target": "ES2022",
"useDefineForClassFields": false
},
"files": ["src/main.ts", "src/polyfills.ts"],
"include": ["src/**/*.d.ts"],
"exclude": ["jest.config.ts", "**/*.test.ts", "**/*.spec.ts"]
}

View File

@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"include": [
"**/*.ts",
"../../../libs/ngrx-notification/backend/src/lib/fake-backend.service.ts"
],
"compilerOptions": {
"types": []
}
}

View File

@@ -0,0 +1,28 @@
{
"extends": "../../../tsconfig.base.json",
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.editor.json"
}
],
"compilerOptions": {
"target": "es2020",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}