├── .gitignore ├── LICENSE ├── README.md ├── part-2 ├── package-lock.json ├── package.json ├── src │ ├── app │ │ ├── app.component.html │ │ ├── app.component.ts │ │ └── app.module.ts │ ├── index.html │ ├── main.ts │ └── polyfills.ts ├── tsconfig.json └── webpack.config.js ├── part-3 ├── package-lock.json ├── package.json ├── src │ ├── app │ │ ├── app.component.html │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ ├── app.routing.ts │ │ ├── home │ │ │ ├── home.component.html │ │ │ ├── home.component.ts │ │ │ └── index.ts │ │ ├── login │ │ │ ├── index.ts │ │ │ ├── login.component.html │ │ │ └── login.component.ts │ │ └── register │ │ │ ├── index.ts │ │ │ ├── register.component.html │ │ │ └── register.component.ts │ ├── index.html │ ├── main.ts │ └── polyfills.ts ├── tsconfig.json └── webpack.config.js ├── part-4 ├── package-lock.json ├── package.json ├── src │ ├── app │ │ ├── _helpers │ │ │ ├── auth.guard.ts │ │ │ ├── error.interceptor.ts │ │ │ ├── fake-backend.ts │ │ │ ├── index.ts │ │ │ └── jwt.interceptor.ts │ │ ├── _services │ │ │ ├── authentication.service.ts │ │ │ └── index.ts │ │ ├── app.component.html │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ ├── app.routing.ts │ │ ├── home │ │ │ ├── home.component.html │ │ │ ├── home.component.ts │ │ │ └── index.ts │ │ ├── login │ │ │ ├── index.ts │ │ │ ├── login.component.html │ │ │ └── login.component.ts │ │ └── register │ │ │ ├── index.ts │ │ │ ├── register.component.html │ │ │ └── register.component.ts │ ├── index.html │ ├── main.ts │ ├── polyfills.ts │ └── typings.d.ts ├── tsconfig.json └── webpack.config.js ├── part-5 ├── package-lock.json ├── package.json ├── src │ ├── app │ │ ├── _helpers │ │ │ ├── auth.guard.ts │ │ │ ├── error.interceptor.ts │ │ │ ├── fake-backend.ts │ │ │ ├── index.ts │ │ │ └── jwt.interceptor.ts │ │ ├── _services │ │ │ ├── authentication.service.ts │ │ │ ├── index.ts │ │ │ └── user.service.ts │ │ ├── app.component.html │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ ├── app.routing.ts │ │ ├── home │ │ │ ├── home.component.html │ │ │ ├── home.component.ts │ │ │ └── index.ts │ │ ├── login │ │ │ ├── index.ts │ │ │ ├── login.component.html │ │ │ └── login.component.ts │ │ └── register │ │ │ ├── index.ts │ │ │ ├── register.component.html │ │ │ └── register.component.ts │ ├── index.html │ ├── main.ts │ ├── polyfills.ts │ └── typings.d.ts ├── tsconfig.json └── webpack.config.js ├── part-6 ├── package-lock.json ├── package.json ├── src │ ├── app │ │ ├── _components │ │ │ ├── alert.component.html │ │ │ ├── alert.component.ts │ │ │ └── index.ts │ │ ├── _helpers │ │ │ ├── auth.guard.ts │ │ │ ├── error.interceptor.ts │ │ │ ├── fake-backend.ts │ │ │ ├── index.ts │ │ │ └── jwt.interceptor.ts │ │ ├── _services │ │ │ ├── alert.service.ts │ │ │ ├── authentication.service.ts │ │ │ ├── index.ts │ │ │ └── user.service.ts │ │ ├── app.component.html │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ ├── app.routing.ts │ │ ├── home │ │ │ ├── home.component.html │ │ │ ├── home.component.ts │ │ │ └── index.ts │ │ ├── login │ │ │ ├── index.ts │ │ │ ├── login.component.html │ │ │ └── login.component.ts │ │ └── register │ │ │ ├── index.ts │ │ │ ├── register.component.html │ │ │ └── register.component.ts │ ├── index.html │ ├── main.ts │ ├── polyfills.ts │ └── typings.d.ts ├── tsconfig.json └── webpack.config.js └── part-7 └── angular7tutorial ├── .editorconfig ├── .gitignore ├── README.md ├── angular.json ├── e2e ├── protractor.conf.js ├── src │ ├── app.e2e-spec.ts │ └── app.po.ts └── tsconfig.e2e.json ├── package-lock.json ├── package.json ├── src ├── app │ ├── _components │ │ ├── alert.component.html │ │ ├── alert.component.ts │ │ └── index.ts │ ├── _helpers │ │ ├── auth.guard.ts │ │ ├── error.interceptor.ts │ │ ├── fake-backend.ts │ │ ├── index.ts │ │ └── jwt.interceptor.ts │ ├── _services │ │ ├── alert.service.ts │ │ ├── authentication.service.ts │ │ ├── index.ts │ │ └── user.service.ts │ ├── app.component.html │ ├── app.component.ts │ ├── app.module.ts │ ├── app.routing.ts │ ├── home │ │ ├── home.component.html │ │ ├── home.component.ts │ │ └── index.ts │ ├── login │ │ ├── index.ts │ │ ├── login.component.html │ │ └── login.component.ts │ └── register │ │ ├── index.ts │ │ ├── register.component.html │ │ └── register.component.ts ├── assets │ └── .gitkeep ├── browserslist ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── karma.conf.js ├── main.ts ├── polyfills.ts ├── styles.less ├── test.ts ├── tsconfig.app.json ├── tsconfig.spec.json └── tslint.json ├── tsconfig.json └── tslint.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules/ 31 | jspm_packages/ 32 | typings/ 33 | 34 | # Optional npm cache directory 35 | .npm 36 | 37 | # Optional REPL history 38 | .node_repl_history 39 | 40 | # Generated files 41 | dist -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2019 Jason Watmore 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # angular-7-tutorial 2 | 3 | A video tutorial series showing how to build an Angular 7 application step by step that supports user registration and login functionality. 4 | 5 | * [Part 1 (Windows) - Setup Development Machine on Windows](https://www.youtube.com/watch?v=FNYsvgmblM0) 6 | * [Part 1 (Mac) - Setup Development Machine on Mac](https://www.youtube.com/watch?v=NLsey2LlJqo) 7 | * [Part 2 - Create Base Project Structure & Webpack Config](https://jasonwatmore.com/post/2019/04/24/angular-7-tutorial-part-2-create-base-project-structure-webpack-config) 8 | * [Part 3 - Add Routing & Multiple Pages](https://jasonwatmore.com/post/2019/04/29/angular-7-tutorial-part-3-add-routing-multiple-pages) 9 | * [Part 4 - Login Form, Authentication Service & Route Guard](https://jasonwatmore.com/post/2019/05/17/angular-7-tutorial-part-4-login-form-authentication-service-route-guard) 10 | * [Part 5 - Registration Form & User Service](https://jasonwatmore.com/post/2019/05/22/angular-7-tutorial-part-5-registration-form-user-service) 11 | * [Part 6 - Home Page & Alert Component](https://jasonwatmore.com/post/2019/05/31/angular-7-tutorial-part-6-home-page-alert-component) 12 | * [Part 7 (Optional) - Migrating to an Angular CLI Project](https://jasonwatmore.com/post/2019/06/13/angular-7-tutorial-part-7-migrating-to-an-angular-cli-project) -------------------------------------------------------------------------------- /part-2/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-7-tutorial", 3 | "version": "1.0.0", 4 | "scripts": { 5 | "start": "webpack-dev-server --mode development --open" 6 | }, 7 | "dependencies": { 8 | "@angular/common": "^7.2.13", 9 | "@angular/compiler": "^7.2.13", 10 | "@angular/core": "^7.2.13", 11 | "@angular/forms": "^7.2.13", 12 | "@angular/platform-browser": "^7.2.13", 13 | "@angular/platform-browser-dynamic": "^7.2.13", 14 | "@angular/router": "^7.2.13", 15 | "core-js": "^3.0.1", 16 | "rxjs": "^6.5.1", 17 | "zone.js": "^0.9.0" 18 | }, 19 | "devDependencies": { 20 | "@types/node": "^11.13.7", 21 | "angular2-template-loader": "^0.6.2", 22 | "html-webpack-plugin": "^3.2.0", 23 | "raw-loader": "^1.0.0", 24 | "ts-loader": "^5.4.3", 25 | "typescript": "^3.4.4", 26 | "webpack": "^4.30.0", 27 | "webpack-cli": "^3.3.1", 28 | "webpack-dev-server": "^3.3.1" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /part-2/src/app/app.component.html: -------------------------------------------------------------------------------- 1 |

Hello Angular 7!

2 | -------------------------------------------------------------------------------- /part-2/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ selector: 'app', templateUrl: 'app.component.html' }) 4 | export class AppComponent {} 5 | -------------------------------------------------------------------------------- /part-2/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | 4 | import { AppComponent } from './app.component'; 5 | 6 | @NgModule({ 7 | imports: [BrowserModule], 8 | declarations: [AppComponent], 9 | bootstrap: [AppComponent] 10 | }) 11 | export class AppModule { } -------------------------------------------------------------------------------- /part-2/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular 7 Tutorial 6 | 7 | 8 | 9 | 10 | 11 | 12 | Loading... 13 | 14 | -------------------------------------------------------------------------------- /part-2/src/main.ts: -------------------------------------------------------------------------------- 1 | import './polyfills'; 2 | 3 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 4 | import { AppModule } from './app/app.module'; 5 | 6 | platformBrowserDynamic().bootstrapModule(AppModule); -------------------------------------------------------------------------------- /part-2/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | import 'core-js/features/reflect'; 2 | import 'zone.js/dist/zone'; -------------------------------------------------------------------------------- /part-2/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "emitDecoratorMetadata": true, 4 | "experimentalDecorators": true, 5 | "target": "ES5" 6 | } 7 | } -------------------------------------------------------------------------------- /part-2/webpack.config.js: -------------------------------------------------------------------------------- 1 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 2 | 3 | module.exports = { 4 | entry: './src/main.ts', 5 | resolve: { 6 | extensions: ['.ts', '.js'] 7 | }, 8 | module: { 9 | rules: [ 10 | { 11 | test: /\.ts$/, 12 | use: ['ts-loader', 'angular2-template-loader'] 13 | }, 14 | { 15 | test: /\.(html|css)$/, 16 | use: 'raw-loader' 17 | } 18 | ] 19 | }, 20 | plugins: [ 21 | new HtmlWebpackPlugin({ template: './src/index.html' }) 22 | ] 23 | } -------------------------------------------------------------------------------- /part-3/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-7-tutorial", 3 | "version": "1.0.0", 4 | "scripts": { 5 | "start": "webpack-dev-server --mode development --open" 6 | }, 7 | "dependencies": { 8 | "@angular/common": "^7.2.13", 9 | "@angular/compiler": "^7.2.13", 10 | "@angular/core": "^7.2.13", 11 | "@angular/forms": "^7.2.13", 12 | "@angular/platform-browser": "^7.2.13", 13 | "@angular/platform-browser-dynamic": "^7.2.13", 14 | "@angular/router": "^7.2.13", 15 | "core-js": "^3.0.1", 16 | "rxjs": "^6.5.1", 17 | "zone.js": "^0.9.0" 18 | }, 19 | "devDependencies": { 20 | "@types/node": "^11.13.7", 21 | "angular2-template-loader": "^0.6.2", 22 | "html-webpack-plugin": "^3.2.0", 23 | "raw-loader": "^1.0.0", 24 | "ts-loader": "^5.4.3", 25 | "typescript": "^3.4.4", 26 | "webpack": "^4.30.0", 27 | "webpack-cli": "^3.3.1", 28 | "webpack-dev-server": "^3.3.1" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /part-3/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 |
12 |
13 |
14 |
15 | 16 |
17 |
18 |
19 |
-------------------------------------------------------------------------------- /part-3/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ selector: 'app', templateUrl: 'app.component.html' }) 4 | export class AppComponent {} 5 | -------------------------------------------------------------------------------- /part-3/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | 4 | import { appRoutingModule } from './app.routing'; 5 | import { AppComponent } from './app.component'; 6 | import { HomeComponent } from './home'; 7 | import { LoginComponent } from './login'; 8 | import { RegisterComponent } from './register'; 9 | 10 | @NgModule({ 11 | imports: [ 12 | BrowserModule, 13 | appRoutingModule 14 | ], 15 | declarations: [ 16 | AppComponent, 17 | HomeComponent, 18 | LoginComponent, 19 | RegisterComponent 20 | ], 21 | bootstrap: [AppComponent] 22 | }) 23 | export class AppModule { }; -------------------------------------------------------------------------------- /part-3/src/app/app.routing.ts: -------------------------------------------------------------------------------- 1 | import { Routes, RouterModule } from '@angular/router'; 2 | 3 | import { HomeComponent } from './home'; 4 | import { LoginComponent } from './login'; 5 | import { RegisterComponent } from './register'; 6 | 7 | const routes: Routes = [ 8 | { path: '', component: HomeComponent }, 9 | { path: 'login', component: LoginComponent }, 10 | { path: 'register', component: RegisterComponent }, 11 | 12 | // otherwise redirect to home 13 | { path: '**', redirectTo: '' } 14 | ]; 15 | 16 | export const appRoutingModule = RouterModule.forRoot(routes); -------------------------------------------------------------------------------- /part-3/src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |

Home Page

-------------------------------------------------------------------------------- /part-3/src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ templateUrl: 'home.component.html' }) 4 | export class HomeComponent {} 5 | -------------------------------------------------------------------------------- /part-3/src/app/home/index.ts: -------------------------------------------------------------------------------- 1 | export * from './home.component'; -------------------------------------------------------------------------------- /part-3/src/app/login/index.ts: -------------------------------------------------------------------------------- 1 | export * from './login.component'; -------------------------------------------------------------------------------- /part-3/src/app/login/login.component.html: -------------------------------------------------------------------------------- 1 |

Login Page

-------------------------------------------------------------------------------- /part-3/src/app/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ templateUrl: 'login.component.html' }) 4 | export class LoginComponent {} 5 | -------------------------------------------------------------------------------- /part-3/src/app/register/index.ts: -------------------------------------------------------------------------------- 1 | export * from './register.component'; -------------------------------------------------------------------------------- /part-3/src/app/register/register.component.html: -------------------------------------------------------------------------------- 1 |

Register Page

-------------------------------------------------------------------------------- /part-3/src/app/register/register.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ templateUrl: 'register.component.html' }) 4 | export class RegisterComponent {} 5 | -------------------------------------------------------------------------------- /part-3/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular 7 Tutorial 6 | 7 | 8 | 9 | 10 | 11 | 12 | Loading... 13 | 14 | -------------------------------------------------------------------------------- /part-3/src/main.ts: -------------------------------------------------------------------------------- 1 | import './polyfills'; 2 | 3 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 4 | import { AppModule } from './app/app.module'; 5 | 6 | platformBrowserDynamic().bootstrapModule(AppModule); -------------------------------------------------------------------------------- /part-3/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | import 'core-js/features/reflect'; 2 | import 'zone.js/dist/zone'; -------------------------------------------------------------------------------- /part-3/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "emitDecoratorMetadata": true, 4 | "experimentalDecorators": true, 5 | "target": "ES5" 6 | } 7 | } -------------------------------------------------------------------------------- /part-3/webpack.config.js: -------------------------------------------------------------------------------- 1 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 2 | 3 | module.exports = { 4 | entry: './src/main.ts', 5 | resolve: { 6 | extensions: ['.ts', '.js'] 7 | }, 8 | module: { 9 | rules: [ 10 | { 11 | test: /\.ts$/, 12 | use: ['ts-loader', 'angular2-template-loader'] 13 | }, 14 | { 15 | test: /\.(html|css)$/, 16 | use: 'raw-loader' 17 | } 18 | ] 19 | }, 20 | plugins: [ 21 | new HtmlWebpackPlugin({ template: './src/index.html' }) 22 | ], 23 | devServer: { 24 | historyApiFallback: true 25 | } 26 | } -------------------------------------------------------------------------------- /part-4/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-7-tutorial", 3 | "version": "1.0.0", 4 | "scripts": { 5 | "start": "webpack-dev-server --mode development --open" 6 | }, 7 | "dependencies": { 8 | "@angular/common": "^7.2.13", 9 | "@angular/compiler": "^7.2.13", 10 | "@angular/core": "^7.2.13", 11 | "@angular/forms": "^7.2.13", 12 | "@angular/platform-browser": "^7.2.13", 13 | "@angular/platform-browser-dynamic": "^7.2.13", 14 | "@angular/router": "^7.2.13", 15 | "core-js": "^3.0.1", 16 | "rxjs": "^6.5.1", 17 | "zone.js": "^0.9.0" 18 | }, 19 | "devDependencies": { 20 | "@types/node": "^11.13.7", 21 | "angular2-template-loader": "^0.6.2", 22 | "html-webpack-plugin": "^3.2.0", 23 | "raw-loader": "^1.0.0", 24 | "ts-loader": "^5.4.3", 25 | "typescript": "^3.4.4", 26 | "webpack": "^4.30.0", 27 | "webpack-cli": "^3.3.1", 28 | "webpack-dev-server": "^3.3.1" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /part-4/src/app/_helpers/auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; 3 | 4 | import { AuthenticationService } from '../_services'; 5 | 6 | @Injectable({ providedIn: 'root' }) 7 | export class AuthGuard implements CanActivate { 8 | constructor( 9 | private router: Router, 10 | private authenticationService: AuthenticationService 11 | ) {} 12 | 13 | canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { 14 | const currentUser = this.authenticationService.currentUserValue; 15 | if (currentUser) { 16 | // authorised so return true 17 | return true; 18 | } 19 | 20 | // not logged in so redirect to login page with the return url 21 | this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }}); 22 | return false; 23 | } 24 | } -------------------------------------------------------------------------------- /part-4/src/app/_helpers/error.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 3 | import { Observable, throwError } from 'rxjs'; 4 | import { catchError } from 'rxjs/operators'; 5 | 6 | import { AuthenticationService } from '../_services'; 7 | 8 | @Injectable() 9 | export class ErrorInterceptor implements HttpInterceptor { 10 | constructor(private authenticationService: AuthenticationService) {} 11 | 12 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 13 | return next.handle(request).pipe(catchError(err => { 14 | if (err.status === 401) { 15 | // auto logout if 401 response returned from api 16 | this.authenticationService.logout(); 17 | location.reload(true); 18 | } 19 | 20 | const error = err.error.message || err.statusText; 21 | return throwError(error); 22 | })) 23 | } 24 | } -------------------------------------------------------------------------------- /part-4/src/app/_helpers/fake-backend.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http'; 3 | import { Observable, of, throwError } from 'rxjs'; 4 | import { delay, mergeMap, materialize, dematerialize } from 'rxjs/operators'; 5 | 6 | let users = [{ id: 1, firstName: 'Jason', lastName: 'Watmore', username: 'test', password: 'test' }]; 7 | 8 | @Injectable() 9 | export class FakeBackendInterceptor implements HttpInterceptor { 10 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 11 | const { url, method, headers, body } = request; 12 | 13 | // wrap in delayed observable to simulate server api call 14 | return of(null) 15 | .pipe(mergeMap(handleRoute)) 16 | .pipe(materialize()) // call materialize and dematerialize to ensure delay even if an error is thrown (https://github.com/Reactive-Extensions/RxJS/issues/648) 17 | .pipe(delay(500)) 18 | .pipe(dematerialize()); 19 | 20 | function handleRoute() { 21 | switch (true) { 22 | case url.endsWith('/users/authenticate') && method === 'POST': 23 | return authenticate(); 24 | default: 25 | // pass through any requests not handled above 26 | return next.handle(request); 27 | } 28 | } 29 | 30 | // route functions 31 | 32 | function authenticate() { 33 | const { username, password } = body; 34 | const user = users.find(x => x.username === username && x.password === password); 35 | if (!user) return error('Username or password is incorrect'); 36 | return ok({ 37 | id: user.id, 38 | username: user.username, 39 | firstName: user.firstName, 40 | lastName: user.lastName, 41 | token: 'fake-jwt-token' 42 | }) 43 | } 44 | 45 | // helper functions 46 | 47 | function ok(body?) { 48 | return of(new HttpResponse({ status: 200, body })) 49 | } 50 | 51 | function error(message) { 52 | return throwError({ error: { message } }); 53 | } 54 | } 55 | } 56 | 57 | export const fakeBackendProvider = { 58 | // use fake backend in place of Http service for backend-less development 59 | provide: HTTP_INTERCEPTORS, 60 | useClass: FakeBackendInterceptor, 61 | multi: true 62 | }; -------------------------------------------------------------------------------- /part-4/src/app/_helpers/index.ts: -------------------------------------------------------------------------------- 1 | export * from './fake-backend'; 2 | export * from './auth.guard'; 3 | export * from './jwt.interceptor'; 4 | export * from './error.interceptor'; -------------------------------------------------------------------------------- /part-4/src/app/_helpers/jwt.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | 5 | import { AuthenticationService } from '../_services'; 6 | 7 | @Injectable() 8 | export class JwtInterceptor implements HttpInterceptor { 9 | constructor(private authenticationService: AuthenticationService) {} 10 | 11 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 12 | // add authorization header with jwt token if available 13 | let currentUser = this.authenticationService.currentUserValue; 14 | if (currentUser && currentUser.token) { 15 | request = request.clone({ 16 | setHeaders: { 17 | Authorization: `Bearer ${currentUser.token}` 18 | } 19 | }); 20 | } 21 | 22 | return next.handle(request); 23 | } 24 | } -------------------------------------------------------------------------------- /part-4/src/app/_services/authentication.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | import { BehaviorSubject, Observable } from 'rxjs'; 4 | import { map } from 'rxjs/operators'; 5 | 6 | @Injectable({ providedIn: 'root' }) 7 | export class AuthenticationService { 8 | private currentUserSubject: BehaviorSubject; 9 | public currentUser: Observable; 10 | 11 | constructor(private http: HttpClient) { 12 | this.currentUserSubject = new BehaviorSubject(JSON.parse(localStorage.getItem('currentUser'))); 13 | this.currentUser = this.currentUserSubject.asObservable(); 14 | } 15 | 16 | public get currentUserValue() { 17 | return this.currentUserSubject.value; 18 | } 19 | 20 | login(username, password) { 21 | return this.http.post(`${config.apiUrl}/users/authenticate`, { username, password }) 22 | .pipe(map(user => { 23 | // store user details and jwt token in local storage to keep user logged in between page refreshes 24 | localStorage.setItem('currentUser', JSON.stringify(user)); 25 | this.currentUserSubject.next(user); 26 | return user; 27 | })); 28 | } 29 | 30 | logout() { 31 | // remove user from local storage and set current user to null 32 | localStorage.removeItem('currentUser'); 33 | this.currentUserSubject.next(null); 34 | } 35 | } -------------------------------------------------------------------------------- /part-4/src/app/_services/index.ts: -------------------------------------------------------------------------------- 1 | export * from './authentication.service'; -------------------------------------------------------------------------------- /part-4/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 |
11 |
12 |
13 |
14 | 15 |
16 |
17 |
18 |
-------------------------------------------------------------------------------- /part-4/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | 4 | import { AuthenticationService } from './_services'; 5 | 6 | @Component({ selector: 'app', templateUrl: 'app.component.html' }) 7 | export class AppComponent { 8 | currentUser: any; 9 | 10 | constructor( 11 | private router: Router, 12 | private authenticationService: AuthenticationService 13 | ) { 14 | this.authenticationService.currentUser.subscribe(x => this.currentUser = x); 15 | } 16 | 17 | logout() { 18 | this.authenticationService.logout(); 19 | this.router.navigate(['/login']); 20 | } 21 | } -------------------------------------------------------------------------------- /part-4/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { ReactiveFormsModule } from '@angular/forms'; 4 | import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; 5 | 6 | // used to create fake backend 7 | import { fakeBackendProvider } from './_helpers'; 8 | 9 | import { appRoutingModule } from './app.routing'; 10 | import { JwtInterceptor, ErrorInterceptor } from './_helpers'; 11 | import { AppComponent } from './app.component'; 12 | import { HomeComponent } from './home'; 13 | import { LoginComponent } from './login'; 14 | import { RegisterComponent } from './register'; 15 | 16 | @NgModule({ 17 | imports: [ 18 | BrowserModule, 19 | ReactiveFormsModule, 20 | HttpClientModule, 21 | appRoutingModule 22 | ], 23 | declarations: [ 24 | AppComponent, 25 | HomeComponent, 26 | LoginComponent, 27 | RegisterComponent 28 | ], 29 | providers: [ 30 | { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, 31 | { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, 32 | 33 | // provider used to create fake backend 34 | fakeBackendProvider 35 | ], 36 | bootstrap: [AppComponent] 37 | }) 38 | export class AppModule { }; -------------------------------------------------------------------------------- /part-4/src/app/app.routing.ts: -------------------------------------------------------------------------------- 1 | import { Routes, RouterModule } from '@angular/router'; 2 | 3 | import { HomeComponent } from './home'; 4 | import { LoginComponent } from './login'; 5 | import { RegisterComponent } from './register'; 6 | import { AuthGuard } from './_helpers'; 7 | 8 | const routes: Routes = [ 9 | { path: '', component: HomeComponent, canActivate: [AuthGuard] }, 10 | { path: 'login', component: LoginComponent }, 11 | { path: 'register', component: RegisterComponent }, 12 | 13 | // otherwise redirect to home 14 | { path: '**', redirectTo: '' } 15 | ]; 16 | 17 | export const appRoutingModule = RouterModule.forRoot(routes); -------------------------------------------------------------------------------- /part-4/src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |

Home Page

-------------------------------------------------------------------------------- /part-4/src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ templateUrl: 'home.component.html' }) 4 | export class HomeComponent {} 5 | -------------------------------------------------------------------------------- /part-4/src/app/home/index.ts: -------------------------------------------------------------------------------- 1 | export * from './home.component'; -------------------------------------------------------------------------------- /part-4/src/app/login/index.ts: -------------------------------------------------------------------------------- 1 | export * from './login.component'; -------------------------------------------------------------------------------- /part-4/src/app/login/login.component.html: -------------------------------------------------------------------------------- 1 |
{{error}}
2 |

Login

3 |
4 |
5 | 6 | 7 |
8 |
Username is required
9 |
10 |
11 |
12 | 13 | 14 |
15 |
Password is required
16 |
17 |
18 |
19 | 23 | Register 24 |
25 |
-------------------------------------------------------------------------------- /part-4/src/app/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router, ActivatedRoute } from '@angular/router'; 3 | import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 4 | import { first } from 'rxjs/operators'; 5 | 6 | import { AuthenticationService } from '../_services' 7 | 8 | @Component({templateUrl: 'login.component.html'}) 9 | export class LoginComponent implements OnInit { 10 | loginForm: FormGroup; 11 | loading = false; 12 | submitted = false; 13 | returnUrl: string; 14 | error: string; 15 | 16 | constructor( 17 | private formBuilder: FormBuilder, 18 | private route: ActivatedRoute, 19 | private router: Router, 20 | private authenticationService: AuthenticationService 21 | ) { 22 | // redirect to home if already logged in 23 | if (this.authenticationService.currentUserValue) { 24 | this.router.navigate(['/']); 25 | } 26 | } 27 | 28 | ngOnInit() { 29 | this.loginForm = this.formBuilder.group({ 30 | username: ['', Validators.required], 31 | password: ['', Validators.required] 32 | }); 33 | 34 | // get return url from route parameters or default to '/' 35 | this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; 36 | } 37 | 38 | // convenience getter for easy access to form fields 39 | get f() { return this.loginForm.controls; } 40 | 41 | onSubmit() { 42 | this.submitted = true; 43 | 44 | // stop here if form is invalid 45 | if (this.loginForm.invalid) { 46 | return; 47 | } 48 | 49 | this.loading = true; 50 | this.authenticationService.login(this.f.username.value, this.f.password.value) 51 | .pipe(first()) 52 | .subscribe( 53 | data => { 54 | this.router.navigate([this.returnUrl]); 55 | }, 56 | error => { 57 | this.error = error; 58 | this.loading = false; 59 | }); 60 | } 61 | } -------------------------------------------------------------------------------- /part-4/src/app/register/index.ts: -------------------------------------------------------------------------------- 1 | export * from './register.component'; -------------------------------------------------------------------------------- /part-4/src/app/register/register.component.html: -------------------------------------------------------------------------------- 1 |

Register Page

-------------------------------------------------------------------------------- /part-4/src/app/register/register.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ templateUrl: 'register.component.html' }) 4 | export class RegisterComponent {} 5 | -------------------------------------------------------------------------------- /part-4/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular 7 Tutorial 6 | 7 | 8 | 9 | 10 | 11 | 12 | Loading... 13 | 14 | -------------------------------------------------------------------------------- /part-4/src/main.ts: -------------------------------------------------------------------------------- 1 | import './polyfills'; 2 | 3 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 4 | import { AppModule } from './app/app.module'; 5 | 6 | platformBrowserDynamic().bootstrapModule(AppModule); -------------------------------------------------------------------------------- /part-4/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | import 'core-js/features/reflect'; 2 | import 'zone.js/dist/zone'; -------------------------------------------------------------------------------- /part-4/src/typings.d.ts: -------------------------------------------------------------------------------- 1 | // so the typescript compiler doesn't complain about the global config object 2 | declare var config: any; -------------------------------------------------------------------------------- /part-4/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "emitDecoratorMetadata": true, 4 | "experimentalDecorators": true, 5 | "target": "ES5" 6 | } 7 | } -------------------------------------------------------------------------------- /part-4/webpack.config.js: -------------------------------------------------------------------------------- 1 | const webpack = require('webpack'); 2 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 3 | 4 | module.exports = { 5 | entry: './src/main.ts', 6 | resolve: { 7 | extensions: ['.ts', '.js'] 8 | }, 9 | module: { 10 | rules: [ 11 | { 12 | test: /\.ts$/, 13 | use: ['ts-loader', 'angular2-template-loader'] 14 | }, 15 | { 16 | test: /\.(html|css)$/, 17 | use: 'raw-loader' 18 | } 19 | ] 20 | }, 21 | plugins: [ 22 | new HtmlWebpackPlugin({ template: './src/index.html' }), 23 | new webpack.DefinePlugin({ 24 | // global app config object 25 | config: JSON.stringify({ 26 | apiUrl: 'http://localhost:4000' 27 | }) 28 | }) 29 | ], 30 | devServer: { 31 | historyApiFallback: true 32 | } 33 | } -------------------------------------------------------------------------------- /part-5/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-7-tutorial", 3 | "version": "1.0.0", 4 | "scripts": { 5 | "start": "webpack-dev-server --mode development --open" 6 | }, 7 | "dependencies": { 8 | "@angular/common": "^7.2.13", 9 | "@angular/compiler": "^7.2.13", 10 | "@angular/core": "^7.2.13", 11 | "@angular/forms": "^7.2.13", 12 | "@angular/platform-browser": "^7.2.13", 13 | "@angular/platform-browser-dynamic": "^7.2.13", 14 | "@angular/router": "^7.2.13", 15 | "core-js": "^3.0.1", 16 | "rxjs": "^6.5.1", 17 | "zone.js": "^0.9.0" 18 | }, 19 | "devDependencies": { 20 | "@types/node": "^11.13.7", 21 | "angular2-template-loader": "^0.6.2", 22 | "html-webpack-plugin": "^3.2.0", 23 | "raw-loader": "^1.0.0", 24 | "ts-loader": "^5.4.3", 25 | "typescript": "^3.4.4", 26 | "webpack": "^4.30.0", 27 | "webpack-cli": "^3.3.1", 28 | "webpack-dev-server": "^3.3.1" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /part-5/src/app/_helpers/auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; 3 | 4 | import { AuthenticationService } from '../_services'; 5 | 6 | @Injectable({ providedIn: 'root' }) 7 | export class AuthGuard implements CanActivate { 8 | constructor( 9 | private router: Router, 10 | private authenticationService: AuthenticationService 11 | ) {} 12 | 13 | canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { 14 | const currentUser = this.authenticationService.currentUserValue; 15 | if (currentUser) { 16 | // authorised so return true 17 | return true; 18 | } 19 | 20 | // not logged in so redirect to login page with the return url 21 | this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }}); 22 | return false; 23 | } 24 | } -------------------------------------------------------------------------------- /part-5/src/app/_helpers/error.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 3 | import { Observable, throwError } from 'rxjs'; 4 | import { catchError } from 'rxjs/operators'; 5 | 6 | import { AuthenticationService } from '../_services'; 7 | 8 | @Injectable() 9 | export class ErrorInterceptor implements HttpInterceptor { 10 | constructor(private authenticationService: AuthenticationService) {} 11 | 12 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 13 | return next.handle(request).pipe(catchError(err => { 14 | if (err.status === 401) { 15 | // auto logout if 401 response returned from api 16 | this.authenticationService.logout(); 17 | location.reload(true); 18 | } 19 | 20 | const error = err.error.message || err.statusText; 21 | return throwError(error); 22 | })) 23 | } 24 | } -------------------------------------------------------------------------------- /part-5/src/app/_helpers/fake-backend.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http'; 3 | import { Observable, of, throwError } from 'rxjs'; 4 | import { delay, mergeMap, materialize, dematerialize } from 'rxjs/operators'; 5 | 6 | // array in local storage for registered users 7 | let users = JSON.parse(localStorage.getItem('users')) || []; 8 | 9 | @Injectable() 10 | export class FakeBackendInterceptor implements HttpInterceptor { 11 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 12 | const { url, method, headers, body } = request; 13 | 14 | // wrap in delayed observable to simulate server api call 15 | return of(null) 16 | .pipe(mergeMap(handleRoute)) 17 | .pipe(materialize()) // call materialize and dematerialize to ensure delay even if an error is thrown (https://github.com/Reactive-Extensions/RxJS/issues/648) 18 | .pipe(delay(500)) 19 | .pipe(dematerialize()); 20 | 21 | function handleRoute() { 22 | switch (true) { 23 | case url.endsWith('/users/authenticate') && method === 'POST': 24 | return authenticate(); 25 | case url.endsWith('/users/register') && method === 'POST': 26 | return register(); 27 | default: 28 | // pass through any requests not handled above 29 | return next.handle(request); 30 | } 31 | } 32 | 33 | // route functions 34 | 35 | function authenticate() { 36 | const { username, password } = body; 37 | const user = users.find(x => x.username === username && x.password === password); 38 | if (!user) return error('Username or password is incorrect'); 39 | return ok({ 40 | id: user.id, 41 | username: user.username, 42 | firstName: user.firstName, 43 | lastName: user.lastName, 44 | token: 'fake-jwt-token' 45 | }) 46 | } 47 | 48 | function register() { 49 | const user = body 50 | 51 | if (users.find(x => x.username === user.username)) { 52 | return error('Username "' + user.username + '" is already taken') 53 | } 54 | 55 | user.id = users.length ? Math.max(...users.map(x => x.id)) + 1 : 1; 56 | users.push(user); 57 | localStorage.setItem('users', JSON.stringify(users)); 58 | 59 | return ok(); 60 | } 61 | 62 | // helper functions 63 | 64 | function ok(body?) { 65 | return of(new HttpResponse({ status: 200, body })) 66 | } 67 | 68 | function error(message) { 69 | return throwError({ error: { message } }); 70 | } 71 | } 72 | } 73 | 74 | export const fakeBackendProvider = { 75 | // use fake backend in place of Http service for backend-less development 76 | provide: HTTP_INTERCEPTORS, 77 | useClass: FakeBackendInterceptor, 78 | multi: true 79 | }; -------------------------------------------------------------------------------- /part-5/src/app/_helpers/index.ts: -------------------------------------------------------------------------------- 1 | export * from './fake-backend'; 2 | export * from './auth.guard'; 3 | export * from './jwt.interceptor'; 4 | export * from './error.interceptor'; -------------------------------------------------------------------------------- /part-5/src/app/_helpers/jwt.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | 5 | import { AuthenticationService } from '../_services'; 6 | 7 | @Injectable() 8 | export class JwtInterceptor implements HttpInterceptor { 9 | constructor(private authenticationService: AuthenticationService) {} 10 | 11 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 12 | // add authorization header with jwt token if available 13 | let currentUser = this.authenticationService.currentUserValue; 14 | if (currentUser && currentUser.token) { 15 | request = request.clone({ 16 | setHeaders: { 17 | Authorization: `Bearer ${currentUser.token}` 18 | } 19 | }); 20 | } 21 | 22 | return next.handle(request); 23 | } 24 | } -------------------------------------------------------------------------------- /part-5/src/app/_services/authentication.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | import { BehaviorSubject, Observable } from 'rxjs'; 4 | import { map } from 'rxjs/operators'; 5 | 6 | @Injectable({ providedIn: 'root' }) 7 | export class AuthenticationService { 8 | private currentUserSubject: BehaviorSubject; 9 | public currentUser: Observable; 10 | 11 | constructor(private http: HttpClient) { 12 | this.currentUserSubject = new BehaviorSubject(JSON.parse(localStorage.getItem('currentUser'))); 13 | this.currentUser = this.currentUserSubject.asObservable(); 14 | } 15 | 16 | public get currentUserValue() { 17 | return this.currentUserSubject.value; 18 | } 19 | 20 | login(username, password) { 21 | return this.http.post(`${config.apiUrl}/users/authenticate`, { username, password }) 22 | .pipe(map(user => { 23 | // store user details and jwt token in local storage to keep user logged in between page refreshes 24 | localStorage.setItem('currentUser', JSON.stringify(user)); 25 | this.currentUserSubject.next(user); 26 | return user; 27 | })); 28 | } 29 | 30 | logout() { 31 | // remove user from local storage and set current user to null 32 | localStorage.removeItem('currentUser'); 33 | this.currentUserSubject.next(null); 34 | } 35 | } -------------------------------------------------------------------------------- /part-5/src/app/_services/index.ts: -------------------------------------------------------------------------------- 1 | export * from './authentication.service'; 2 | export * from './user.service'; -------------------------------------------------------------------------------- /part-5/src/app/_services/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | 4 | @Injectable({ providedIn: 'root' }) 5 | export class UserService { 6 | constructor(private http: HttpClient) { } 7 | 8 | getAll() { 9 | return this.http.get(`${config.apiUrl}/users`); 10 | } 11 | 12 | register(user) { 13 | return this.http.post(`${config.apiUrl}/users/register`, user); 14 | } 15 | 16 | delete(id) { 17 | return this.http.delete(`${config.apiUrl}/users/${id}`); 18 | } 19 | } -------------------------------------------------------------------------------- /part-5/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 |
11 |
12 |
13 |
14 | 15 |
16 |
17 |
18 |
-------------------------------------------------------------------------------- /part-5/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | 4 | import { AuthenticationService } from './_services'; 5 | 6 | @Component({ selector: 'app', templateUrl: 'app.component.html' }) 7 | export class AppComponent { 8 | currentUser: any; 9 | 10 | constructor( 11 | private router: Router, 12 | private authenticationService: AuthenticationService 13 | ) { 14 | this.authenticationService.currentUser.subscribe(x => this.currentUser = x); 15 | } 16 | 17 | logout() { 18 | this.authenticationService.logout(); 19 | this.router.navigate(['/login']); 20 | } 21 | } -------------------------------------------------------------------------------- /part-5/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { ReactiveFormsModule } from '@angular/forms'; 4 | import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; 5 | 6 | // used to create fake backend 7 | import { fakeBackendProvider } from './_helpers'; 8 | 9 | import { appRoutingModule } from './app.routing'; 10 | import { JwtInterceptor, ErrorInterceptor } from './_helpers'; 11 | import { AppComponent } from './app.component'; 12 | import { HomeComponent } from './home'; 13 | import { LoginComponent } from './login'; 14 | import { RegisterComponent } from './register'; 15 | 16 | @NgModule({ 17 | imports: [ 18 | BrowserModule, 19 | ReactiveFormsModule, 20 | HttpClientModule, 21 | appRoutingModule 22 | ], 23 | declarations: [ 24 | AppComponent, 25 | HomeComponent, 26 | LoginComponent, 27 | RegisterComponent 28 | ], 29 | providers: [ 30 | { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, 31 | { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, 32 | 33 | // provider used to create fake backend 34 | fakeBackendProvider 35 | ], 36 | bootstrap: [AppComponent] 37 | }) 38 | export class AppModule { }; -------------------------------------------------------------------------------- /part-5/src/app/app.routing.ts: -------------------------------------------------------------------------------- 1 | import { Routes, RouterModule } from '@angular/router'; 2 | 3 | import { HomeComponent } from './home'; 4 | import { LoginComponent } from './login'; 5 | import { RegisterComponent } from './register'; 6 | import { AuthGuard } from './_helpers'; 7 | 8 | const routes: Routes = [ 9 | { path: '', component: HomeComponent, canActivate: [AuthGuard] }, 10 | { path: 'login', component: LoginComponent }, 11 | { path: 'register', component: RegisterComponent }, 12 | 13 | // otherwise redirect to home 14 | { path: '**', redirectTo: '' } 15 | ]; 16 | 17 | export const appRoutingModule = RouterModule.forRoot(routes); -------------------------------------------------------------------------------- /part-5/src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |

Home Page

-------------------------------------------------------------------------------- /part-5/src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ templateUrl: 'home.component.html' }) 4 | export class HomeComponent {} 5 | -------------------------------------------------------------------------------- /part-5/src/app/home/index.ts: -------------------------------------------------------------------------------- 1 | export * from './home.component'; -------------------------------------------------------------------------------- /part-5/src/app/login/index.ts: -------------------------------------------------------------------------------- 1 | export * from './login.component'; -------------------------------------------------------------------------------- /part-5/src/app/login/login.component.html: -------------------------------------------------------------------------------- 1 |
{{error}}
2 |
{{success}}
3 |

Login

4 |
5 |
6 | 7 | 8 |
9 |
Username is required
10 |
11 |
12 |
13 | 14 | 15 |
16 |
Password is required
17 |
18 |
19 |
20 | 24 | Register 25 |
26 |
-------------------------------------------------------------------------------- /part-5/src/app/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router, ActivatedRoute } from '@angular/router'; 3 | import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 4 | import { first } from 'rxjs/operators'; 5 | 6 | import { AuthenticationService } from '../_services' 7 | 8 | @Component({templateUrl: 'login.component.html'}) 9 | export class LoginComponent implements OnInit { 10 | loginForm: FormGroup; 11 | loading = false; 12 | submitted = false; 13 | returnUrl: string; 14 | error: string; 15 | success: string 16 | 17 | constructor( 18 | private formBuilder: FormBuilder, 19 | private route: ActivatedRoute, 20 | private router: Router, 21 | private authenticationService: AuthenticationService 22 | ) { 23 | // redirect to home if already logged in 24 | if (this.authenticationService.currentUserValue) { 25 | this.router.navigate(['/']); 26 | } 27 | } 28 | 29 | ngOnInit() { 30 | this.loginForm = this.formBuilder.group({ 31 | username: ['', Validators.required], 32 | password: ['', Validators.required] 33 | }); 34 | 35 | // get return url from route parameters or default to '/' 36 | this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; 37 | 38 | // show success message on registration 39 | if (this.route.snapshot.queryParams['registered']) { 40 | this.success = 'Registration successful'; 41 | } 42 | } 43 | 44 | // convenience getter for easy access to form fields 45 | get f() { return this.loginForm.controls; } 46 | 47 | onSubmit() { 48 | this.submitted = true; 49 | 50 | // reset alerts on submit 51 | this.error = null; 52 | this.success = null; 53 | 54 | // stop here if form is invalid 55 | if (this.loginForm.invalid) { 56 | return; 57 | } 58 | 59 | this.loading = true; 60 | this.authenticationService.login(this.f.username.value, this.f.password.value) 61 | .pipe(first()) 62 | .subscribe( 63 | data => { 64 | this.router.navigate([this.returnUrl]); 65 | }, 66 | error => { 67 | this.error = error; 68 | this.loading = false; 69 | }); 70 | } 71 | } -------------------------------------------------------------------------------- /part-5/src/app/register/index.ts: -------------------------------------------------------------------------------- 1 | export * from './register.component'; -------------------------------------------------------------------------------- /part-5/src/app/register/register.component.html: -------------------------------------------------------------------------------- 1 |
{{error}}
2 |

Register

3 |
4 |
5 | 6 | 7 |
8 |
First Name is required
9 |
10 |
11 |
12 | 13 | 14 |
15 |
Last Name is required
16 |
17 |
18 |
19 | 20 | 21 |
22 |
Username is required
23 |
24 |
25 |
26 | 27 | 28 |
29 |
Password is required
30 |
Password must be at least 6 characters
31 |
32 |
33 |
34 | 38 | Cancel 39 |
40 |
-------------------------------------------------------------------------------- /part-5/src/app/register/register.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 4 | import { first } from 'rxjs/operators'; 5 | 6 | import { UserService, AuthenticationService } from '../_services'; 7 | 8 | @Component({ templateUrl: 'register.component.html' }) 9 | export class RegisterComponent implements OnInit { 10 | registerForm: FormGroup; 11 | loading = false; 12 | submitted = false; 13 | error: string; 14 | 15 | constructor( 16 | private formBuilder: FormBuilder, 17 | private router: Router, 18 | private authenticationService: AuthenticationService, 19 | private userService: UserService 20 | ) { 21 | // redirect to home if already logged in 22 | if (this.authenticationService.currentUserValue) { 23 | this.router.navigate(['/']); 24 | } 25 | } 26 | 27 | ngOnInit() { 28 | this.registerForm = this.formBuilder.group({ 29 | firstName: ['', Validators.required], 30 | lastName: ['', Validators.required], 31 | username: ['', Validators.required], 32 | password: ['', [Validators.required, Validators.minLength(6)]] 33 | }); 34 | } 35 | 36 | // convenience getter for easy access to form fields 37 | get f() { return this.registerForm.controls; } 38 | 39 | onSubmit() { 40 | this.submitted = true; 41 | 42 | // stop here if form is invalid 43 | if (this.registerForm.invalid) { 44 | return; 45 | } 46 | 47 | this.loading = true; 48 | this.userService.register(this.registerForm.value) 49 | .pipe(first()) 50 | .subscribe( 51 | data => { 52 | this.router.navigate(['/login'], { queryParams: { registered: true }}); 53 | }, 54 | error => { 55 | this.error = error; 56 | this.loading = false; 57 | }); 58 | } 59 | } -------------------------------------------------------------------------------- /part-5/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular 7 Tutorial 6 | 7 | 8 | 9 | 10 | 11 | 12 | Loading... 13 | 14 | -------------------------------------------------------------------------------- /part-5/src/main.ts: -------------------------------------------------------------------------------- 1 | import './polyfills'; 2 | 3 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 4 | import { AppModule } from './app/app.module'; 5 | 6 | platformBrowserDynamic().bootstrapModule(AppModule); -------------------------------------------------------------------------------- /part-5/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | import 'core-js/features/reflect'; 2 | import 'zone.js/dist/zone'; -------------------------------------------------------------------------------- /part-5/src/typings.d.ts: -------------------------------------------------------------------------------- 1 | // so the typescript compiler doesn't complain about the global config object 2 | declare var config: any; -------------------------------------------------------------------------------- /part-5/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "emitDecoratorMetadata": true, 4 | "experimentalDecorators": true, 5 | "target": "ES5" 6 | } 7 | } -------------------------------------------------------------------------------- /part-5/webpack.config.js: -------------------------------------------------------------------------------- 1 | const webpack = require('webpack'); 2 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 3 | 4 | module.exports = { 5 | entry: './src/main.ts', 6 | resolve: { 7 | extensions: ['.ts', '.js'] 8 | }, 9 | module: { 10 | rules: [ 11 | { 12 | test: /\.ts$/, 13 | use: ['ts-loader', 'angular2-template-loader'] 14 | }, 15 | { 16 | test: /\.(html|css)$/, 17 | use: 'raw-loader' 18 | } 19 | ] 20 | }, 21 | plugins: [ 22 | new HtmlWebpackPlugin({ template: './src/index.html' }), 23 | new webpack.DefinePlugin({ 24 | // global app config object 25 | config: JSON.stringify({ 26 | apiUrl: 'http://localhost:4000' 27 | }) 28 | }) 29 | ], 30 | devServer: { 31 | historyApiFallback: true 32 | } 33 | } -------------------------------------------------------------------------------- /part-6/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-7-tutorial", 3 | "version": "1.0.0", 4 | "scripts": { 5 | "start": "webpack-dev-server --mode development --open" 6 | }, 7 | "dependencies": { 8 | "@angular/common": "^7.2.13", 9 | "@angular/compiler": "^7.2.13", 10 | "@angular/core": "^7.2.13", 11 | "@angular/forms": "^7.2.13", 12 | "@angular/platform-browser": "^7.2.13", 13 | "@angular/platform-browser-dynamic": "^7.2.13", 14 | "@angular/router": "^7.2.13", 15 | "core-js": "^3.0.1", 16 | "rxjs": "^6.5.1", 17 | "zone.js": "^0.9.0" 18 | }, 19 | "devDependencies": { 20 | "@types/node": "^11.13.7", 21 | "angular2-template-loader": "^0.6.2", 22 | "html-webpack-plugin": "^3.2.0", 23 | "raw-loader": "^1.0.0", 24 | "ts-loader": "^5.4.3", 25 | "typescript": "^3.4.4", 26 | "webpack": "^4.30.0", 27 | "webpack-cli": "^3.3.1", 28 | "webpack-dev-server": "^3.3.1" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /part-6/src/app/_components/alert.component.html: -------------------------------------------------------------------------------- 1 |
{{message.text}}
-------------------------------------------------------------------------------- /part-6/src/app/_components/alert.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, OnDestroy } from '@angular/core'; 2 | import { Subscription } from 'rxjs'; 3 | 4 | import { AlertService } from '../_services'; 5 | 6 | @Component({ selector: 'alert', templateUrl: 'alert.component.html' }) 7 | export class AlertComponent implements OnInit, OnDestroy { 8 | private subscription: Subscription; 9 | message: any; 10 | 11 | constructor(private alertService: AlertService) { } 12 | 13 | ngOnInit() { 14 | this.subscription = this.alertService.getAlert() 15 | .subscribe(message => { 16 | switch (message && message.type) { 17 | case 'success': 18 | message.cssClass = 'alert alert-success'; 19 | break; 20 | case 'error': 21 | message.cssClass = 'alert alert-danger'; 22 | break; 23 | } 24 | 25 | this.message = message; 26 | }); 27 | } 28 | 29 | ngOnDestroy() { 30 | this.subscription.unsubscribe(); 31 | } 32 | } -------------------------------------------------------------------------------- /part-6/src/app/_components/index.ts: -------------------------------------------------------------------------------- 1 | export * from './alert.component'; -------------------------------------------------------------------------------- /part-6/src/app/_helpers/auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; 3 | 4 | import { AuthenticationService } from '../_services'; 5 | 6 | @Injectable({ providedIn: 'root' }) 7 | export class AuthGuard implements CanActivate { 8 | constructor( 9 | private router: Router, 10 | private authenticationService: AuthenticationService 11 | ) {} 12 | 13 | canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { 14 | const currentUser = this.authenticationService.currentUserValue; 15 | if (currentUser) { 16 | // authorised so return true 17 | return true; 18 | } 19 | 20 | // not logged in so redirect to login page with the return url 21 | this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }}); 22 | return false; 23 | } 24 | } -------------------------------------------------------------------------------- /part-6/src/app/_helpers/error.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 3 | import { Observable, throwError } from 'rxjs'; 4 | import { catchError } from 'rxjs/operators'; 5 | 6 | import { AuthenticationService } from '../_services'; 7 | 8 | @Injectable() 9 | export class ErrorInterceptor implements HttpInterceptor { 10 | constructor(private authenticationService: AuthenticationService) {} 11 | 12 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 13 | return next.handle(request).pipe(catchError(err => { 14 | if (err.status === 401) { 15 | // auto logout if 401 response returned from api 16 | this.authenticationService.logout(); 17 | location.reload(true); 18 | } 19 | 20 | const error = err.error.message || err.statusText; 21 | return throwError(error); 22 | })) 23 | } 24 | } -------------------------------------------------------------------------------- /part-6/src/app/_helpers/fake-backend.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http'; 3 | import { Observable, of, throwError } from 'rxjs'; 4 | import { delay, mergeMap, materialize, dematerialize } from 'rxjs/operators'; 5 | 6 | // array in local storage for registered users 7 | let users = JSON.parse(localStorage.getItem('users')) || []; 8 | 9 | @Injectable() 10 | export class FakeBackendInterceptor implements HttpInterceptor { 11 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 12 | const { url, method, headers, body } = request; 13 | 14 | // wrap in delayed observable to simulate server api call 15 | return of(null) 16 | .pipe(mergeMap(handleRoute)) 17 | .pipe(materialize()) // call materialize and dematerialize to ensure delay even if an error is thrown (https://github.com/Reactive-Extensions/RxJS/issues/648) 18 | .pipe(delay(500)) 19 | .pipe(dematerialize()); 20 | 21 | function handleRoute() { 22 | switch (true) { 23 | case url.endsWith('/users/authenticate') && method === 'POST': 24 | return authenticate(); 25 | case url.endsWith('/users/register') && method === 'POST': 26 | return register(); 27 | case url.endsWith('/users') && method === 'GET': 28 | return getUsers(); 29 | case url.match(/\/users\/\d+$/) && method === 'DELETE': 30 | return deleteUser(); 31 | default: 32 | // pass through any requests not handled above 33 | return next.handle(request); 34 | } 35 | } 36 | 37 | // route functions 38 | 39 | function authenticate() { 40 | const { username, password } = body; 41 | const user = users.find(x => x.username === username && x.password === password); 42 | if (!user) return error('Username or password is incorrect'); 43 | return ok({ 44 | id: user.id, 45 | username: user.username, 46 | firstName: user.firstName, 47 | lastName: user.lastName, 48 | token: 'fake-jwt-token' 49 | }) 50 | } 51 | 52 | function register() { 53 | const user = body 54 | 55 | if (users.find(x => x.username === user.username)) { 56 | return error('Username "' + user.username + '" is already taken') 57 | } 58 | 59 | user.id = users.length ? Math.max(...users.map(x => x.id)) + 1 : 1; 60 | users.push(user); 61 | localStorage.setItem('users', JSON.stringify(users)); 62 | 63 | return ok(); 64 | } 65 | 66 | function getUsers() { 67 | if (!isLoggedIn()) return unauthorized(); 68 | return ok(users); 69 | } 70 | 71 | function deleteUser() { 72 | if (!isLoggedIn()) return unauthorized(); 73 | 74 | users = users.filter(x => x.id !== idFromUrl()); 75 | localStorage.setItem('users', JSON.stringify(users)); 76 | return ok(); 77 | } 78 | 79 | // helper functions 80 | 81 | function ok(body?) { 82 | return of(new HttpResponse({ status: 200, body })) 83 | } 84 | 85 | function error(message) { 86 | return throwError({ error: { message } }); 87 | } 88 | 89 | function unauthorized() { 90 | return throwError({ status: 401, error: { message: 'Unauthorised' } }); 91 | } 92 | 93 | function isLoggedIn() { 94 | return headers.get('Authorization') === 'Bearer fake-jwt-token'; 95 | } 96 | 97 | function idFromUrl() { 98 | const urlParts = url.split('/'); 99 | return parseInt(urlParts[urlParts.length - 1]); 100 | } 101 | } 102 | } 103 | 104 | export const fakeBackendProvider = { 105 | // use fake backend in place of Http service for backend-less development 106 | provide: HTTP_INTERCEPTORS, 107 | useClass: FakeBackendInterceptor, 108 | multi: true 109 | }; -------------------------------------------------------------------------------- /part-6/src/app/_helpers/index.ts: -------------------------------------------------------------------------------- 1 | export * from './fake-backend'; 2 | export * from './auth.guard'; 3 | export * from './jwt.interceptor'; 4 | export * from './error.interceptor'; -------------------------------------------------------------------------------- /part-6/src/app/_helpers/jwt.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | 5 | import { AuthenticationService } from '../_services'; 6 | 7 | @Injectable() 8 | export class JwtInterceptor implements HttpInterceptor { 9 | constructor(private authenticationService: AuthenticationService) {} 10 | 11 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 12 | // add authorization header with jwt token if available 13 | let currentUser = this.authenticationService.currentUserValue; 14 | if (currentUser && currentUser.token) { 15 | request = request.clone({ 16 | setHeaders: { 17 | Authorization: `Bearer ${currentUser.token}` 18 | } 19 | }); 20 | } 21 | 22 | return next.handle(request); 23 | } 24 | } -------------------------------------------------------------------------------- /part-6/src/app/_services/alert.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router, NavigationStart } from '@angular/router'; 3 | import { Observable, Subject } from 'rxjs'; 4 | 5 | @Injectable({ providedIn: 'root' }) 6 | export class AlertService { 7 | private subject = new Subject(); 8 | private keepAfterRouteChange = false; 9 | 10 | constructor(private router: Router) { 11 | // clear alert messages on route change unless 'keepAfterRouteChange' flag is true 12 | this.router.events.subscribe(event => { 13 | if (event instanceof NavigationStart) { 14 | if (this.keepAfterRouteChange) { 15 | // only keep for a single route change 16 | this.keepAfterRouteChange = false; 17 | } else { 18 | // clear alert message 19 | this.clear(); 20 | } 21 | } 22 | }); 23 | } 24 | 25 | getAlert(): Observable { 26 | return this.subject.asObservable(); 27 | } 28 | 29 | success(message: string, keepAfterRouteChange = false) { 30 | this.keepAfterRouteChange = keepAfterRouteChange; 31 | this.subject.next({ type: 'success', text: message }); 32 | } 33 | 34 | error(message: string, keepAfterRouteChange = false) { 35 | this.keepAfterRouteChange = keepAfterRouteChange; 36 | this.subject.next({ type: 'error', text: message }); 37 | } 38 | 39 | clear() { 40 | // clear by calling subject.next() without parameters 41 | this.subject.next(); 42 | } 43 | } -------------------------------------------------------------------------------- /part-6/src/app/_services/authentication.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | import { BehaviorSubject, Observable } from 'rxjs'; 4 | import { map } from 'rxjs/operators'; 5 | 6 | @Injectable({ providedIn: 'root' }) 7 | export class AuthenticationService { 8 | private currentUserSubject: BehaviorSubject; 9 | public currentUser: Observable; 10 | 11 | constructor(private http: HttpClient) { 12 | this.currentUserSubject = new BehaviorSubject(JSON.parse(localStorage.getItem('currentUser'))); 13 | this.currentUser = this.currentUserSubject.asObservable(); 14 | } 15 | 16 | public get currentUserValue() { 17 | return this.currentUserSubject.value; 18 | } 19 | 20 | login(username, password) { 21 | return this.http.post(`${config.apiUrl}/users/authenticate`, { username, password }) 22 | .pipe(map(user => { 23 | // store user details and jwt token in local storage to keep user logged in between page refreshes 24 | localStorage.setItem('currentUser', JSON.stringify(user)); 25 | this.currentUserSubject.next(user); 26 | return user; 27 | })); 28 | } 29 | 30 | logout() { 31 | // remove user from local storage and set current user to null 32 | localStorage.removeItem('currentUser'); 33 | this.currentUserSubject.next(null); 34 | } 35 | } -------------------------------------------------------------------------------- /part-6/src/app/_services/index.ts: -------------------------------------------------------------------------------- 1 | export * from './authentication.service'; 2 | export * from './user.service'; 3 | export * from './alert.service'; -------------------------------------------------------------------------------- /part-6/src/app/_services/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | 4 | @Injectable({ providedIn: 'root' }) 5 | export class UserService { 6 | constructor(private http: HttpClient) { } 7 | 8 | getAll() { 9 | return this.http.get(`${config.apiUrl}/users`); 10 | } 11 | 12 | register(user) { 13 | return this.http.post(`${config.apiUrl}/users/register`, user); 14 | } 15 | 16 | delete(id) { 17 | return this.http.delete(`${config.apiUrl}/users/${id}`); 18 | } 19 | } -------------------------------------------------------------------------------- /part-6/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 |
11 |
12 |
13 |
14 | 15 | 16 |
17 |
18 |
19 |
-------------------------------------------------------------------------------- /part-6/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | 4 | import { AuthenticationService } from './_services'; 5 | 6 | @Component({ selector: 'app', templateUrl: 'app.component.html' }) 7 | export class AppComponent { 8 | currentUser: any; 9 | 10 | constructor( 11 | private router: Router, 12 | private authenticationService: AuthenticationService 13 | ) { 14 | this.authenticationService.currentUser.subscribe(x => this.currentUser = x); 15 | } 16 | 17 | logout() { 18 | this.authenticationService.logout(); 19 | this.router.navigate(['/login']); 20 | } 21 | } -------------------------------------------------------------------------------- /part-6/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { ReactiveFormsModule } from '@angular/forms'; 4 | import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; 5 | 6 | // used to create fake backend 7 | import { fakeBackendProvider } from './_helpers'; 8 | 9 | import { appRoutingModule } from './app.routing'; 10 | import { JwtInterceptor, ErrorInterceptor } from './_helpers'; 11 | import { AppComponent } from './app.component'; 12 | import { HomeComponent } from './home'; 13 | import { LoginComponent } from './login'; 14 | import { RegisterComponent } from './register'; 15 | import { AlertComponent } from './_components'; 16 | 17 | @NgModule({ 18 | imports: [ 19 | BrowserModule, 20 | ReactiveFormsModule, 21 | HttpClientModule, 22 | appRoutingModule 23 | ], 24 | declarations: [ 25 | AppComponent, 26 | HomeComponent, 27 | LoginComponent, 28 | RegisterComponent, 29 | AlertComponent 30 | ], 31 | providers: [ 32 | { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, 33 | { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, 34 | 35 | // provider used to create fake backend 36 | fakeBackendProvider 37 | ], 38 | bootstrap: [AppComponent] 39 | }) 40 | export class AppModule { }; -------------------------------------------------------------------------------- /part-6/src/app/app.routing.ts: -------------------------------------------------------------------------------- 1 | import { Routes, RouterModule } from '@angular/router'; 2 | 3 | import { HomeComponent } from './home'; 4 | import { LoginComponent } from './login'; 5 | import { RegisterComponent } from './register'; 6 | import { AuthGuard } from './_helpers'; 7 | 8 | const routes: Routes = [ 9 | { path: '', component: HomeComponent, canActivate: [AuthGuard] }, 10 | { path: 'login', component: LoginComponent }, 11 | { path: 'register', component: RegisterComponent }, 12 | 13 | // otherwise redirect to home 14 | { path: '**', redirectTo: '' } 15 | ]; 16 | 17 | export const appRoutingModule = RouterModule.forRoot(routes); -------------------------------------------------------------------------------- /part-6/src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |

Hi {{currentUser.firstName}}!

2 |

You're logged in with Angular 7!!

3 |

All registered users:

4 |
    5 |
  • 6 | {{user.username}} ({{user.firstName}} {{user.lastName}}) 7 | - Delete 8 |
  • 9 |
-------------------------------------------------------------------------------- /part-6/src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { first } from 'rxjs/operators'; 3 | 4 | import { UserService, AuthenticationService } from '../_services'; 5 | 6 | @Component({ templateUrl: 'home.component.html' }) 7 | export class HomeComponent implements OnInit { 8 | currentUser: any; 9 | users = []; 10 | 11 | constructor( 12 | private authenticationService: AuthenticationService, 13 | private userService: UserService 14 | ) { 15 | this.currentUser = this.authenticationService.currentUserValue; 16 | } 17 | 18 | ngOnInit() { 19 | this.loadAllUsers(); 20 | } 21 | 22 | deleteUser(id: number) { 23 | this.userService.delete(id) 24 | .pipe(first()) 25 | .subscribe(() => this.loadAllUsers()); 26 | } 27 | 28 | private loadAllUsers() { 29 | this.userService.getAll() 30 | .pipe(first()) 31 | .subscribe(users => this.users = users); 32 | } 33 | } -------------------------------------------------------------------------------- /part-6/src/app/home/index.ts: -------------------------------------------------------------------------------- 1 | export * from './home.component'; -------------------------------------------------------------------------------- /part-6/src/app/login/index.ts: -------------------------------------------------------------------------------- 1 | export * from './login.component'; -------------------------------------------------------------------------------- /part-6/src/app/login/login.component.html: -------------------------------------------------------------------------------- 1 |

Login

2 |
3 |
4 | 5 | 6 |
7 |
Username is required
8 |
9 |
10 |
11 | 12 | 13 |
14 |
Password is required
15 |
16 |
17 |
18 | 22 | Register 23 |
24 |
-------------------------------------------------------------------------------- /part-6/src/app/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router, ActivatedRoute } from '@angular/router'; 3 | import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 4 | import { first } from 'rxjs/operators'; 5 | 6 | import { AuthenticationService, AlertService } from '../_services' 7 | 8 | @Component({templateUrl: 'login.component.html'}) 9 | export class LoginComponent implements OnInit { 10 | loginForm: FormGroup; 11 | loading = false; 12 | submitted = false; 13 | returnUrl: string; 14 | 15 | constructor( 16 | private formBuilder: FormBuilder, 17 | private route: ActivatedRoute, 18 | private router: Router, 19 | private authenticationService: AuthenticationService, 20 | private alertService: AlertService 21 | ) { 22 | // redirect to home if already logged in 23 | if (this.authenticationService.currentUserValue) { 24 | this.router.navigate(['/']); 25 | } 26 | } 27 | 28 | ngOnInit() { 29 | this.loginForm = this.formBuilder.group({ 30 | username: ['', Validators.required], 31 | password: ['', Validators.required] 32 | }); 33 | 34 | // get return url from route parameters or default to '/' 35 | this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; 36 | } 37 | 38 | // convenience getter for easy access to form fields 39 | get f() { return this.loginForm.controls; } 40 | 41 | onSubmit() { 42 | this.submitted = true; 43 | 44 | // reset alerts on submit 45 | this.alertService.clear(); 46 | 47 | // stop here if form is invalid 48 | if (this.loginForm.invalid) { 49 | return; 50 | } 51 | 52 | this.loading = true; 53 | this.authenticationService.login(this.f.username.value, this.f.password.value) 54 | .pipe(first()) 55 | .subscribe( 56 | data => { 57 | this.router.navigate([this.returnUrl]); 58 | }, 59 | error => { 60 | this.alertService.error(error); 61 | this.loading = false; 62 | }); 63 | } 64 | } -------------------------------------------------------------------------------- /part-6/src/app/register/index.ts: -------------------------------------------------------------------------------- 1 | export * from './register.component'; -------------------------------------------------------------------------------- /part-6/src/app/register/register.component.html: -------------------------------------------------------------------------------- 1 |

Register

2 |
3 |
4 | 5 | 6 |
7 |
First Name is required
8 |
9 |
10 |
11 | 12 | 13 |
14 |
Last Name is required
15 |
16 |
17 |
18 | 19 | 20 |
21 |
Username is required
22 |
23 |
24 |
25 | 26 | 27 |
28 |
Password is required
29 |
Password must be at least 6 characters
30 |
31 |
32 |
33 | 37 | Cancel 38 |
39 |
-------------------------------------------------------------------------------- /part-6/src/app/register/register.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 4 | import { first } from 'rxjs/operators'; 5 | 6 | import { UserService, AuthenticationService, AlertService } from '../_services'; 7 | 8 | @Component({ templateUrl: 'register.component.html' }) 9 | export class RegisterComponent implements OnInit { 10 | registerForm: FormGroup; 11 | loading = false; 12 | submitted = false; 13 | 14 | constructor( 15 | private formBuilder: FormBuilder, 16 | private router: Router, 17 | private authenticationService: AuthenticationService, 18 | private userService: UserService, 19 | private alertService: AlertService 20 | ) { 21 | // redirect to home if already logged in 22 | if (this.authenticationService.currentUserValue) { 23 | this.router.navigate(['/']); 24 | } 25 | } 26 | 27 | ngOnInit() { 28 | this.registerForm = this.formBuilder.group({ 29 | firstName: ['', Validators.required], 30 | lastName: ['', Validators.required], 31 | username: ['', Validators.required], 32 | password: ['', [Validators.required, Validators.minLength(6)]] 33 | }); 34 | } 35 | 36 | // convenience getter for easy access to form fields 37 | get f() { return this.registerForm.controls; } 38 | 39 | onSubmit() { 40 | this.submitted = true; 41 | 42 | // reset alerts on submit 43 | this.alertService.clear(); 44 | 45 | // stop here if form is invalid 46 | if (this.registerForm.invalid) { 47 | return; 48 | } 49 | 50 | this.loading = true; 51 | this.userService.register(this.registerForm.value) 52 | .pipe(first()) 53 | .subscribe( 54 | data => { 55 | this.alertService.success('Registration successful', true); 56 | this.router.navigate(['/login'], { queryParams: { registered: true }}); 57 | }, 58 | error => { 59 | this.alertService.error(error); 60 | this.loading = false; 61 | }); 62 | } 63 | } -------------------------------------------------------------------------------- /part-6/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular 7 Tutorial 6 | 7 | 8 | 9 | 10 | 11 | 12 | Loading... 13 | 14 | -------------------------------------------------------------------------------- /part-6/src/main.ts: -------------------------------------------------------------------------------- 1 | import './polyfills'; 2 | 3 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 4 | import { AppModule } from './app/app.module'; 5 | 6 | platformBrowserDynamic().bootstrapModule(AppModule); -------------------------------------------------------------------------------- /part-6/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | import 'core-js/features/reflect'; 2 | import 'zone.js/dist/zone'; -------------------------------------------------------------------------------- /part-6/src/typings.d.ts: -------------------------------------------------------------------------------- 1 | // so the typescript compiler doesn't complain about the global config object 2 | declare var config: any; -------------------------------------------------------------------------------- /part-6/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "emitDecoratorMetadata": true, 4 | "experimentalDecorators": true, 5 | "target": "ES5" 6 | } 7 | } -------------------------------------------------------------------------------- /part-6/webpack.config.js: -------------------------------------------------------------------------------- 1 | const webpack = require('webpack'); 2 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 3 | 4 | module.exports = { 5 | entry: './src/main.ts', 6 | resolve: { 7 | extensions: ['.ts', '.js'] 8 | }, 9 | module: { 10 | rules: [ 11 | { 12 | test: /\.ts$/, 13 | use: ['ts-loader', 'angular2-template-loader'] 14 | }, 15 | { 16 | test: /\.(html|css)$/, 17 | use: 'raw-loader' 18 | } 19 | ] 20 | }, 21 | plugins: [ 22 | new HtmlWebpackPlugin({ template: './src/index.html' }), 23 | new webpack.DefinePlugin({ 24 | // global app config object 25 | config: JSON.stringify({ 26 | apiUrl: 'http://localhost:4000' 27 | }) 28 | }) 29 | ], 30 | devServer: { 31 | historyApiFallback: true 32 | } 33 | } -------------------------------------------------------------------------------- /part-7/angular7tutorial/.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | # Only exists if Bazel was run 8 | /bazel-out 9 | 10 | # dependencies 11 | /node_modules 12 | 13 | # profiling files 14 | chrome-profiler-events.json 15 | speed-measure-plugin.json 16 | 17 | # IDEs and editors 18 | /.idea 19 | .project 20 | .classpath 21 | .c9/ 22 | *.launch 23 | .settings/ 24 | *.sublime-workspace 25 | 26 | # IDE - VSCode 27 | .vscode/* 28 | !.vscode/settings.json 29 | !.vscode/tasks.json 30 | !.vscode/launch.json 31 | !.vscode/extensions.json 32 | .history/* 33 | 34 | # misc 35 | /.sass-cache 36 | /connect.lock 37 | /coverage 38 | /libpeerconnection.log 39 | npm-debug.log 40 | yarn-error.log 41 | testem.log 42 | /typings 43 | 44 | # System Files 45 | .DS_Store 46 | Thumbs.db 47 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/README.md: -------------------------------------------------------------------------------- 1 | # Angular7tutorial 2 | 3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.3.9. 4 | 5 | ## Development server 6 | 7 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 8 | 9 | ## Code scaffolding 10 | 11 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. 12 | 13 | ## Build 14 | 15 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. 16 | 17 | ## Running unit tests 18 | 19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 20 | 21 | ## Running end-to-end tests 22 | 23 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 24 | 25 | ## Further help 26 | 27 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). 28 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "angular7tutorial": { 7 | "root": "", 8 | "sourceRoot": "src", 9 | "projectType": "application", 10 | "prefix": "app", 11 | "schematics": { 12 | "@schematics/angular:component": { 13 | "style": "less" 14 | } 15 | }, 16 | "architect": { 17 | "build": { 18 | "builder": "@angular-devkit/build-angular:browser", 19 | "options": { 20 | "outputPath": "dist/angular7tutorial", 21 | "index": "src/index.html", 22 | "main": "src/main.ts", 23 | "polyfills": "src/polyfills.ts", 24 | "tsConfig": "src/tsconfig.app.json", 25 | "assets": [ 26 | "src/favicon.ico", 27 | "src/assets" 28 | ], 29 | "styles": [ 30 | "src/styles.less" 31 | ], 32 | "scripts": [], 33 | "es5BrowserSupport": true 34 | }, 35 | "configurations": { 36 | "production": { 37 | "fileReplacements": [ 38 | { 39 | "replace": "src/environments/environment.ts", 40 | "with": "src/environments/environment.prod.ts" 41 | } 42 | ], 43 | "optimization": true, 44 | "outputHashing": "all", 45 | "sourceMap": false, 46 | "extractCss": true, 47 | "namedChunks": false, 48 | "aot": true, 49 | "extractLicenses": true, 50 | "vendorChunk": false, 51 | "buildOptimizer": true, 52 | "budgets": [ 53 | { 54 | "type": "initial", 55 | "maximumWarning": "2mb", 56 | "maximumError": "5mb" 57 | } 58 | ] 59 | } 60 | } 61 | }, 62 | "serve": { 63 | "builder": "@angular-devkit/build-angular:dev-server", 64 | "options": { 65 | "browserTarget": "angular7tutorial:build" 66 | }, 67 | "configurations": { 68 | "production": { 69 | "browserTarget": "angular7tutorial:build:production" 70 | } 71 | } 72 | }, 73 | "extract-i18n": { 74 | "builder": "@angular-devkit/build-angular:extract-i18n", 75 | "options": { 76 | "browserTarget": "angular7tutorial:build" 77 | } 78 | }, 79 | "test": { 80 | "builder": "@angular-devkit/build-angular:karma", 81 | "options": { 82 | "main": "src/test.ts", 83 | "polyfills": "src/polyfills.ts", 84 | "tsConfig": "src/tsconfig.spec.json", 85 | "karmaConfig": "src/karma.conf.js", 86 | "styles": [ 87 | "src/styles.less" 88 | ], 89 | "scripts": [], 90 | "assets": [ 91 | "src/favicon.ico", 92 | "src/assets" 93 | ] 94 | } 95 | }, 96 | "lint": { 97 | "builder": "@angular-devkit/build-angular:tslint", 98 | "options": { 99 | "tsConfig": [ 100 | "src/tsconfig.app.json", 101 | "src/tsconfig.spec.json" 102 | ], 103 | "exclude": [ 104 | "**/node_modules/**" 105 | ] 106 | } 107 | } 108 | } 109 | }, 110 | "angular7tutorial-e2e": { 111 | "root": "e2e/", 112 | "projectType": "application", 113 | "prefix": "", 114 | "architect": { 115 | "e2e": { 116 | "builder": "@angular-devkit/build-angular:protractor", 117 | "options": { 118 | "protractorConfig": "e2e/protractor.conf.js", 119 | "devServerTarget": "angular7tutorial:serve" 120 | }, 121 | "configurations": { 122 | "production": { 123 | "devServerTarget": "angular7tutorial:serve:production" 124 | } 125 | } 126 | }, 127 | "lint": { 128 | "builder": "@angular-devkit/build-angular:tslint", 129 | "options": { 130 | "tsConfig": "e2e/tsconfig.e2e.json", 131 | "exclude": [ 132 | "**/node_modules/**" 133 | ] 134 | } 135 | } 136 | } 137 | } 138 | }, 139 | "defaultProject": "angular7tutorial" 140 | } -------------------------------------------------------------------------------- /part-7/angular7tutorial/e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require('jasmine-spec-reporter'); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: [ 9 | './src/**/*.e2e-spec.ts' 10 | ], 11 | capabilities: { 12 | 'browserName': 'chrome' 13 | }, 14 | directConnect: true, 15 | baseUrl: 'http://localhost:4200/', 16 | framework: 'jasmine', 17 | jasmineNodeOpts: { 18 | showColors: true, 19 | defaultTimeoutInterval: 30000, 20 | print: function() {} 21 | }, 22 | onPrepare() { 23 | require('ts-node').register({ 24 | project: require('path').join(__dirname, './tsconfig.e2e.json') 25 | }); 26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; -------------------------------------------------------------------------------- /part-7/angular7tutorial/e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | import { browser, logging } from 'protractor'; 3 | 4 | describe('workspace-project App', () => { 5 | let page: AppPage; 6 | 7 | beforeEach(() => { 8 | page = new AppPage(); 9 | }); 10 | 11 | it('should display welcome message', () => { 12 | page.navigateTo(); 13 | expect(page.getTitleText()).toEqual('Welcome to angular7tutorial!'); 14 | }); 15 | 16 | afterEach(async () => { 17 | // Assert that there are no errors emitted from the browser 18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER); 19 | expect(logs).not.toContain(jasmine.objectContaining({ 20 | level: logging.Level.SEVERE, 21 | } as logging.Entry)); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get(browser.baseUrl) as Promise; 6 | } 7 | 8 | getTitleText() { 9 | return element(by.css('app-root h1')).getText() as Promise; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } -------------------------------------------------------------------------------- /part-7/angular7tutorial/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular7tutorial", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "test": "ng test", 9 | "lint": "ng lint", 10 | "e2e": "ng e2e" 11 | }, 12 | "private": true, 13 | "dependencies": { 14 | "@angular/animations": "~7.2.0", 15 | "@angular/common": "~7.2.0", 16 | "@angular/compiler": "~7.2.0", 17 | "@angular/core": "~7.2.0", 18 | "@angular/forms": "~7.2.0", 19 | "@angular/platform-browser": "~7.2.0", 20 | "@angular/platform-browser-dynamic": "~7.2.0", 21 | "@angular/router": "~7.2.0", 22 | "core-js": "^2.5.4", 23 | "rxjs": "~6.3.3", 24 | "tslib": "^1.9.0", 25 | "zone.js": "~0.8.26" 26 | }, 27 | "devDependencies": { 28 | "@angular-devkit/build-angular": "~0.13.0", 29 | "@angular/cli": "~7.3.9", 30 | "@angular/compiler-cli": "~7.2.0", 31 | "@angular/language-service": "~7.2.0", 32 | "@types/node": "~8.9.4", 33 | "@types/jasmine": "~2.8.8", 34 | "@types/jasminewd2": "~2.0.3", 35 | "codelyzer": "~4.5.0", 36 | "jasmine-core": "~2.99.1", 37 | "jasmine-spec-reporter": "~4.2.1", 38 | "karma": "~4.0.0", 39 | "karma-chrome-launcher": "~2.2.0", 40 | "karma-coverage-istanbul-reporter": "~2.0.1", 41 | "karma-jasmine": "~1.1.2", 42 | "karma-jasmine-html-reporter": "^0.2.2", 43 | "protractor": "~5.4.0", 44 | "ts-node": "~7.0.0", 45 | "tslint": "~5.11.0", 46 | "typescript": "~3.2.2" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/_components/alert.component.html: -------------------------------------------------------------------------------- 1 |
{{message.text}}
-------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/_components/alert.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, OnDestroy } from '@angular/core'; 2 | import { Subscription } from 'rxjs'; 3 | 4 | import { AlertService } from '../_services'; 5 | 6 | @Component({ selector: 'alert', templateUrl: 'alert.component.html' }) 7 | export class AlertComponent implements OnInit, OnDestroy { 8 | private subscription: Subscription; 9 | message: any; 10 | 11 | constructor(private alertService: AlertService) { } 12 | 13 | ngOnInit() { 14 | this.subscription = this.alertService.getAlert() 15 | .subscribe(message => { 16 | switch (message && message.type) { 17 | case 'success': 18 | message.cssClass = 'alert alert-success'; 19 | break; 20 | case 'error': 21 | message.cssClass = 'alert alert-danger'; 22 | break; 23 | } 24 | 25 | this.message = message; 26 | }); 27 | } 28 | 29 | ngOnDestroy() { 30 | this.subscription.unsubscribe(); 31 | } 32 | } -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/_components/index.ts: -------------------------------------------------------------------------------- 1 | export * from './alert.component'; -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/_helpers/auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; 3 | 4 | import { AuthenticationService } from '../_services'; 5 | 6 | @Injectable({ providedIn: 'root' }) 7 | export class AuthGuard implements CanActivate { 8 | constructor( 9 | private router: Router, 10 | private authenticationService: AuthenticationService 11 | ) {} 12 | 13 | canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { 14 | const currentUser = this.authenticationService.currentUserValue; 15 | if (currentUser) { 16 | // authorised so return true 17 | return true; 18 | } 19 | 20 | // not logged in so redirect to login page with the return url 21 | this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }}); 22 | return false; 23 | } 24 | } -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/_helpers/error.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 3 | import { Observable, throwError } from 'rxjs'; 4 | import { catchError } from 'rxjs/operators'; 5 | 6 | import { AuthenticationService } from '../_services'; 7 | 8 | @Injectable() 9 | export class ErrorInterceptor implements HttpInterceptor { 10 | constructor(private authenticationService: AuthenticationService) {} 11 | 12 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 13 | return next.handle(request).pipe(catchError(err => { 14 | if (err.status === 401) { 15 | // auto logout if 401 response returned from api 16 | this.authenticationService.logout(); 17 | location.reload(true); 18 | } 19 | 20 | const error = err.error.message || err.statusText; 21 | return throwError(error); 22 | })) 23 | } 24 | } -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/_helpers/fake-backend.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http'; 3 | import { Observable, of, throwError } from 'rxjs'; 4 | import { delay, mergeMap, materialize, dematerialize } from 'rxjs/operators'; 5 | 6 | // array in local storage for registered users 7 | let users = JSON.parse(localStorage.getItem('users')) || []; 8 | 9 | @Injectable() 10 | export class FakeBackendInterceptor implements HttpInterceptor { 11 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 12 | const { url, method, headers, body } = request; 13 | 14 | // wrap in delayed observable to simulate server api call 15 | return of(null) 16 | .pipe(mergeMap(handleRoute)) 17 | .pipe(materialize()) // call materialize and dematerialize to ensure delay even if an error is thrown (https://github.com/Reactive-Extensions/RxJS/issues/648) 18 | .pipe(delay(500)) 19 | .pipe(dematerialize()); 20 | 21 | function handleRoute() { 22 | switch (true) { 23 | case url.endsWith('/users/authenticate') && method === 'POST': 24 | return authenticate(); 25 | case url.endsWith('/users/register') && method === 'POST': 26 | return register(); 27 | case url.endsWith('/users') && method === 'GET': 28 | return getUsers(); 29 | case url.match(/\/users\/\d+$/) && method === 'DELETE': 30 | return deleteUser(); 31 | default: 32 | // pass through any requests not handled above 33 | return next.handle(request); 34 | } 35 | } 36 | 37 | // route functions 38 | 39 | function authenticate() { 40 | const { username, password } = body; 41 | const user = users.find(x => x.username === username && x.password === password); 42 | if (!user) return error('Username or password is incorrect'); 43 | return ok({ 44 | id: user.id, 45 | username: user.username, 46 | firstName: user.firstName, 47 | lastName: user.lastName, 48 | token: 'fake-jwt-token' 49 | }) 50 | } 51 | 52 | function register() { 53 | const user = body 54 | 55 | if (users.find(x => x.username === user.username)) { 56 | return error('Username "' + user.username + '" is already taken') 57 | } 58 | 59 | user.id = users.length ? Math.max(...users.map(x => x.id)) + 1 : 1; 60 | users.push(user); 61 | localStorage.setItem('users', JSON.stringify(users)); 62 | 63 | return ok(); 64 | } 65 | 66 | function getUsers() { 67 | if (!isLoggedIn()) return unauthorized(); 68 | return ok(users); 69 | } 70 | 71 | function deleteUser() { 72 | if (!isLoggedIn()) return unauthorized(); 73 | 74 | users = users.filter(x => x.id !== idFromUrl()); 75 | localStorage.setItem('users', JSON.stringify(users)); 76 | return ok(); 77 | } 78 | 79 | // helper functions 80 | 81 | function ok(body?) { 82 | return of(new HttpResponse({ status: 200, body })) 83 | } 84 | 85 | function error(message) { 86 | return throwError({ error: { message } }); 87 | } 88 | 89 | function unauthorized() { 90 | return throwError({ status: 401, error: { message: 'Unauthorised' } }); 91 | } 92 | 93 | function isLoggedIn() { 94 | return headers.get('Authorization') === 'Bearer fake-jwt-token'; 95 | } 96 | 97 | function idFromUrl() { 98 | const urlParts = url.split('/'); 99 | return parseInt(urlParts[urlParts.length - 1]); 100 | } 101 | } 102 | } 103 | 104 | export const fakeBackendProvider = { 105 | // use fake backend in place of Http service for backend-less development 106 | provide: HTTP_INTERCEPTORS, 107 | useClass: FakeBackendInterceptor, 108 | multi: true 109 | }; -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/_helpers/index.ts: -------------------------------------------------------------------------------- 1 | export * from './fake-backend'; 2 | export * from './auth.guard'; 3 | export * from './jwt.interceptor'; 4 | export * from './error.interceptor'; -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/_helpers/jwt.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | 5 | import { AuthenticationService } from '../_services'; 6 | 7 | @Injectable() 8 | export class JwtInterceptor implements HttpInterceptor { 9 | constructor(private authenticationService: AuthenticationService) {} 10 | 11 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 12 | // add authorization header with jwt token if available 13 | let currentUser = this.authenticationService.currentUserValue; 14 | if (currentUser && currentUser.token) { 15 | request = request.clone({ 16 | setHeaders: { 17 | Authorization: `Bearer ${currentUser.token}` 18 | } 19 | }); 20 | } 21 | 22 | return next.handle(request); 23 | } 24 | } -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/_services/alert.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router, NavigationStart } from '@angular/router'; 3 | import { Observable, Subject } from 'rxjs'; 4 | 5 | @Injectable({ providedIn: 'root' }) 6 | export class AlertService { 7 | private subject = new Subject(); 8 | private keepAfterRouteChange = false; 9 | 10 | constructor(private router: Router) { 11 | // clear alert messages on route change unless 'keepAfterRouteChange' flag is true 12 | this.router.events.subscribe(event => { 13 | if (event instanceof NavigationStart) { 14 | if (this.keepAfterRouteChange) { 15 | // only keep for a single route change 16 | this.keepAfterRouteChange = false; 17 | } else { 18 | // clear alert message 19 | this.clear(); 20 | } 21 | } 22 | }); 23 | } 24 | 25 | getAlert(): Observable { 26 | return this.subject.asObservable(); 27 | } 28 | 29 | success(message: string, keepAfterRouteChange = false) { 30 | this.keepAfterRouteChange = keepAfterRouteChange; 31 | this.subject.next({ type: 'success', text: message }); 32 | } 33 | 34 | error(message: string, keepAfterRouteChange = false) { 35 | this.keepAfterRouteChange = keepAfterRouteChange; 36 | this.subject.next({ type: 'error', text: message }); 37 | } 38 | 39 | clear() { 40 | // clear by calling subject.next() without parameters 41 | this.subject.next(); 42 | } 43 | } -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/_services/authentication.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | import { BehaviorSubject, Observable } from 'rxjs'; 4 | import { map } from 'rxjs/operators'; 5 | 6 | import { environment } from '@environments/environment'; 7 | 8 | @Injectable({ providedIn: 'root' }) 9 | export class AuthenticationService { 10 | private currentUserSubject: BehaviorSubject; 11 | public currentUser: Observable; 12 | 13 | constructor(private http: HttpClient) { 14 | this.currentUserSubject = new BehaviorSubject(JSON.parse(localStorage.getItem('currentUser'))); 15 | this.currentUser = this.currentUserSubject.asObservable(); 16 | } 17 | 18 | public get currentUserValue() { 19 | return this.currentUserSubject.value; 20 | } 21 | 22 | login(username, password) { 23 | return this.http.post(`${environment.apiUrl}/users/authenticate`, { username, password }) 24 | .pipe(map(user => { 25 | // store user details and jwt token in local storage to keep user logged in between page refreshes 26 | localStorage.setItem('currentUser', JSON.stringify(user)); 27 | this.currentUserSubject.next(user); 28 | return user; 29 | })); 30 | } 31 | 32 | logout() { 33 | // remove user from local storage and set current user to null 34 | localStorage.removeItem('currentUser'); 35 | this.currentUserSubject.next(null); 36 | } 37 | } -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/_services/index.ts: -------------------------------------------------------------------------------- 1 | export * from './authentication.service'; 2 | export * from './user.service'; 3 | export * from './alert.service'; -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/_services/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | 4 | import { environment } from '@environments/environment'; 5 | 6 | @Injectable({ providedIn: 'root' }) 7 | export class UserService { 8 | constructor(private http: HttpClient) { } 9 | 10 | getAll() { 11 | return this.http.get(`${environment.apiUrl}/users`); 12 | } 13 | 14 | register(user) { 15 | return this.http.post(`${environment.apiUrl}/users/register`, user); 16 | } 17 | 18 | delete(id) { 19 | return this.http.delete(`${environment.apiUrl}/users/${id}`); 20 | } 21 | } -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 |
11 |
12 |
13 |
14 | 15 | 16 |
17 |
18 |
19 |
-------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | 4 | import { AuthenticationService } from './_services'; 5 | 6 | @Component({ selector: 'app', templateUrl: 'app.component.html' }) 7 | export class AppComponent { 8 | currentUser: any; 9 | 10 | constructor( 11 | private router: Router, 12 | private authenticationService: AuthenticationService 13 | ) { 14 | this.authenticationService.currentUser.subscribe(x => this.currentUser = x); 15 | } 16 | 17 | logout() { 18 | this.authenticationService.logout(); 19 | this.router.navigate(['/login']); 20 | } 21 | } -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { ReactiveFormsModule } from '@angular/forms'; 4 | import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; 5 | 6 | // used to create fake backend 7 | import { fakeBackendProvider } from './_helpers'; 8 | 9 | import { appRoutingModule } from './app.routing'; 10 | import { JwtInterceptor, ErrorInterceptor } from './_helpers'; 11 | import { AppComponent } from './app.component'; 12 | import { HomeComponent } from './home'; 13 | import { LoginComponent } from './login'; 14 | import { RegisterComponent } from './register'; 15 | import { AlertComponent } from './_components'; 16 | 17 | @NgModule({ 18 | imports: [ 19 | BrowserModule, 20 | ReactiveFormsModule, 21 | HttpClientModule, 22 | appRoutingModule 23 | ], 24 | declarations: [ 25 | AppComponent, 26 | HomeComponent, 27 | LoginComponent, 28 | RegisterComponent, 29 | AlertComponent 30 | ], 31 | providers: [ 32 | { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, 33 | { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, 34 | 35 | // provider used to create fake backend 36 | fakeBackendProvider 37 | ], 38 | bootstrap: [AppComponent] 39 | }) 40 | export class AppModule { }; -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/app.routing.ts: -------------------------------------------------------------------------------- 1 | import { Routes, RouterModule } from '@angular/router'; 2 | 3 | import { HomeComponent } from './home'; 4 | import { LoginComponent } from './login'; 5 | import { RegisterComponent } from './register'; 6 | import { AuthGuard } from './_helpers'; 7 | 8 | const routes: Routes = [ 9 | { path: '', component: HomeComponent, canActivate: [AuthGuard] }, 10 | { path: 'login', component: LoginComponent }, 11 | { path: 'register', component: RegisterComponent }, 12 | 13 | // otherwise redirect to home 14 | { path: '**', redirectTo: '' } 15 | ]; 16 | 17 | export const appRoutingModule = RouterModule.forRoot(routes); -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |

Hi {{currentUser.firstName}}!

2 |

You're logged in with Angular 7!!

3 |

All registered users:

4 |
    5 |
  • 6 | {{user.username}} ({{user.firstName}} {{user.lastName}}) 7 | - Delete 8 |
  • 9 |
-------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { first } from 'rxjs/operators'; 3 | 4 | import { UserService, AuthenticationService } from '../_services'; 5 | 6 | @Component({ templateUrl: 'home.component.html' }) 7 | export class HomeComponent implements OnInit { 8 | currentUser: any; 9 | users = []; 10 | 11 | constructor( 12 | private authenticationService: AuthenticationService, 13 | private userService: UserService 14 | ) { 15 | this.currentUser = this.authenticationService.currentUserValue; 16 | } 17 | 18 | ngOnInit() { 19 | this.loadAllUsers(); 20 | } 21 | 22 | deleteUser(id: number) { 23 | this.userService.delete(id) 24 | .pipe(first()) 25 | .subscribe(() => this.loadAllUsers()); 26 | } 27 | 28 | private loadAllUsers() { 29 | this.userService.getAll() 30 | .pipe(first()) 31 | .subscribe(users => this.users = users); 32 | } 33 | } -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/home/index.ts: -------------------------------------------------------------------------------- 1 | export * from './home.component'; -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/login/index.ts: -------------------------------------------------------------------------------- 1 | export * from './login.component'; -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/login/login.component.html: -------------------------------------------------------------------------------- 1 |

Login

2 |
3 |
4 | 5 | 6 |
7 |
Username is required
8 |
9 |
10 |
11 | 12 | 13 |
14 |
Password is required
15 |
16 |
17 |
18 | 22 | Register 23 |
24 |
-------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router, ActivatedRoute } from '@angular/router'; 3 | import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 4 | import { first } from 'rxjs/operators'; 5 | 6 | import { AuthenticationService, AlertService } from '../_services' 7 | 8 | @Component({templateUrl: 'login.component.html'}) 9 | export class LoginComponent implements OnInit { 10 | loginForm: FormGroup; 11 | loading = false; 12 | submitted = false; 13 | returnUrl: string; 14 | 15 | constructor( 16 | private formBuilder: FormBuilder, 17 | private route: ActivatedRoute, 18 | private router: Router, 19 | private authenticationService: AuthenticationService, 20 | private alertService: AlertService 21 | ) { 22 | // redirect to home if already logged in 23 | if (this.authenticationService.currentUserValue) { 24 | this.router.navigate(['/']); 25 | } 26 | } 27 | 28 | ngOnInit() { 29 | this.loginForm = this.formBuilder.group({ 30 | username: ['', Validators.required], 31 | password: ['', Validators.required] 32 | }); 33 | 34 | // get return url from route parameters or default to '/' 35 | this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; 36 | } 37 | 38 | // convenience getter for easy access to form fields 39 | get f() { return this.loginForm.controls; } 40 | 41 | onSubmit() { 42 | this.submitted = true; 43 | 44 | // reset alerts on submit 45 | this.alertService.clear(); 46 | 47 | // stop here if form is invalid 48 | if (this.loginForm.invalid) { 49 | return; 50 | } 51 | 52 | this.loading = true; 53 | this.authenticationService.login(this.f.username.value, this.f.password.value) 54 | .pipe(first()) 55 | .subscribe( 56 | data => { 57 | this.router.navigate([this.returnUrl]); 58 | }, 59 | error => { 60 | this.alertService.error(error); 61 | this.loading = false; 62 | }); 63 | } 64 | } -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/register/index.ts: -------------------------------------------------------------------------------- 1 | export * from './register.component'; -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/register/register.component.html: -------------------------------------------------------------------------------- 1 |

Register

2 |
3 |
4 | 5 | 6 |
7 |
First Name is required
8 |
9 |
10 |
11 | 12 | 13 |
14 |
Last Name is required
15 |
16 |
17 |
18 | 19 | 20 |
21 |
Username is required
22 |
23 |
24 |
25 | 26 | 27 |
28 |
Password is required
29 |
Password must be at least 6 characters
30 |
31 |
32 |
33 | 37 | Cancel 38 |
39 |
-------------------------------------------------------------------------------- /part-7/angular7tutorial/src/app/register/register.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 4 | import { first } from 'rxjs/operators'; 5 | 6 | import { UserService, AuthenticationService, AlertService } from '../_services'; 7 | 8 | @Component({ templateUrl: 'register.component.html' }) 9 | export class RegisterComponent implements OnInit { 10 | registerForm: FormGroup; 11 | loading = false; 12 | submitted = false; 13 | 14 | constructor( 15 | private formBuilder: FormBuilder, 16 | private router: Router, 17 | private authenticationService: AuthenticationService, 18 | private userService: UserService, 19 | private alertService: AlertService 20 | ) { 21 | // redirect to home if already logged in 22 | if (this.authenticationService.currentUserValue) { 23 | this.router.navigate(['/']); 24 | } 25 | } 26 | 27 | ngOnInit() { 28 | this.registerForm = this.formBuilder.group({ 29 | firstName: ['', Validators.required], 30 | lastName: ['', Validators.required], 31 | username: ['', Validators.required], 32 | password: ['', [Validators.required, Validators.minLength(6)]] 33 | }); 34 | } 35 | 36 | // convenience getter for easy access to form fields 37 | get f() { return this.registerForm.controls; } 38 | 39 | onSubmit() { 40 | this.submitted = true; 41 | 42 | // reset alerts on submit 43 | this.alertService.clear(); 44 | 45 | // stop here if form is invalid 46 | if (this.registerForm.invalid) { 47 | return; 48 | } 49 | 50 | this.loading = true; 51 | this.userService.register(this.registerForm.value) 52 | .pipe(first()) 53 | .subscribe( 54 | data => { 55 | this.alertService.success('Registration successful', true); 56 | this.router.navigate(['/login'], { queryParams: { registered: true }}); 57 | }, 58 | error => { 59 | this.alertService.error(error); 60 | this.loading = false; 61 | }); 62 | } 63 | } -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cornflourblue/angular-7-tutorial/284655908432c55c5f23988146aa423b92d37b56/part-7/angular7tutorial/src/assets/.gitkeep -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/browserslist: -------------------------------------------------------------------------------- 1 | # This file is currently used by autoprefixer to adjust CSS to support the below specified browsers 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | # 5 | # For IE 9-11 support, please remove 'not' from the last line of the file and adjust as needed 6 | 7 | > 0.5% 8 | last 2 versions 9 | Firefox ESR 10 | not dead 11 | not IE 9-11 -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | apiUrl: 'http://localhost:4000' 4 | }; 5 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false, 7 | apiUrl: 'http://localhost:4000' 8 | }; 9 | 10 | /* 11 | * For easier debugging in development mode, you can import the following file 12 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 13 | * 14 | * This import should be commented out in production mode because it will have a negative impact 15 | * on performance if an error is thrown. 16 | */ 17 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 18 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cornflourblue/angular-7-tutorial/284655908432c55c5f23988146aa423b92d37b56/part-7/angular7tutorial/src/favicon.ico -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular 7 Tutorial 6 | 7 | 8 | 9 | 10 | 11 | 12 | Loading... 13 | 14 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, '../coverage/angular7tutorial'), 20 | reports: ['html', 'lcovonly', 'text-summary'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false, 30 | restartOnFileChange: true 31 | }); 32 | }; 33 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.error(err)); 13 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 22 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 23 | 24 | /** 25 | * Web Animations `@angular/platform-browser/animations` 26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 28 | */ 29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 30 | 31 | /** 32 | * By default, zone.js will patch all possible macroTask and DomEvents 33 | * user can disable parts of macroTask/DomEvents patch by setting following flags 34 | * because those flags need to be set before `zone.js` being loaded, and webpack 35 | * will put import in the top of bundle, so user need to create a separate file 36 | * in this directory (for example: zone-flags.ts), and put the following flags 37 | * into that file, and then add the following code before importing zone.js. 38 | * import './zone-flags.ts'; 39 | * 40 | * The flags allowed in zone-flags.ts are listed here. 41 | * 42 | * The following flags will work for all browsers. 43 | * 44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 46 | * (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 47 | * 48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 50 | * 51 | * (window as any).__Zone_enable_cross_context_check = true; 52 | * 53 | */ 54 | 55 | /*************************************************************************************************** 56 | * Zone JS is required by default for Angular itself. 57 | */ 58 | import 'zone.js/dist/zone'; // Included with Angular CLI. 59 | 60 | 61 | /*************************************************************************************************** 62 | * APPLICATION IMPORTS 63 | */ 64 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/styles.less: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/zone-testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: any; 11 | 12 | // First, initialize the Angular testing environment. 13 | getTestBed().initTestEnvironment( 14 | BrowserDynamicTestingModule, 15 | platformBrowserDynamicTesting() 16 | ); 17 | // Then we find all the tests. 18 | const context = require.context('./', true, /\.spec\.ts$/); 19 | // And load the modules. 20 | context.keys().map(context); 21 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "types": [] 6 | }, 7 | "exclude": [ 8 | "test.ts", 9 | "**/*.spec.ts" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 8 | ] 9 | }, 10 | "files": [ 11 | "test.ts", 12 | "polyfills.ts" 13 | ], 14 | "include": [ 15 | "**/*.spec.ts", 16 | "**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/src/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tslint.json", 3 | "rules": { 4 | "directive-selector": [ 5 | true, 6 | "attribute", 7 | "app", 8 | "camelCase" 9 | ], 10 | "component-selector": [ 11 | true, 12 | "element", 13 | "app", 14 | "kebab-case" 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "module": "es2015", 9 | "moduleResolution": "node", 10 | "emitDecoratorMetadata": true, 11 | "experimentalDecorators": true, 12 | "importHelpers": true, 13 | "target": "es5", 14 | "typeRoots": [ 15 | "node_modules/@types" 16 | ], 17 | "lib": [ 18 | "es2018", 19 | "dom" 20 | ], 21 | "paths": { 22 | "@environments/*": ["src/environments/*"] 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /part-7/angular7tutorial/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rulesDirectory": [ 4 | "codelyzer" 5 | ], 6 | "rules": { 7 | "array-type": false, 8 | "arrow-parens": false, 9 | "deprecation": { 10 | "severity": "warn" 11 | }, 12 | "import-blacklist": [ 13 | true, 14 | "rxjs/Rx" 15 | ], 16 | "interface-name": false, 17 | "max-classes-per-file": false, 18 | "max-line-length": [ 19 | true, 20 | 140 21 | ], 22 | "member-access": false, 23 | "member-ordering": [ 24 | true, 25 | { 26 | "order": [ 27 | "static-field", 28 | "instance-field", 29 | "static-method", 30 | "instance-method" 31 | ] 32 | } 33 | ], 34 | "no-consecutive-blank-lines": false, 35 | "no-console": [ 36 | true, 37 | "debug", 38 | "info", 39 | "time", 40 | "timeEnd", 41 | "trace" 42 | ], 43 | "no-empty": false, 44 | "no-inferrable-types": [ 45 | true, 46 | "ignore-params" 47 | ], 48 | "no-non-null-assertion": true, 49 | "no-redundant-jsdoc": true, 50 | "no-switch-case-fall-through": true, 51 | "no-use-before-declare": true, 52 | "no-var-requires": false, 53 | "object-literal-key-quotes": [ 54 | true, 55 | "as-needed" 56 | ], 57 | "object-literal-sort-keys": false, 58 | "ordered-imports": false, 59 | "quotemark": [ 60 | true, 61 | "single" 62 | ], 63 | "trailing-comma": false, 64 | "no-output-on-prefix": true, 65 | "use-input-property-decorator": true, 66 | "use-output-property-decorator": true, 67 | "use-host-property-decorator": true, 68 | "no-input-rename": true, 69 | "no-output-rename": true, 70 | "use-life-cycle-interface": true, 71 | "use-pipe-transform-interface": true, 72 | "component-class-suffix": true, 73 | "directive-class-suffix": true 74 | } 75 | } 76 | --------------------------------------------------------------------------------