This commit is contained in:
JakubWalkowiak 2022-02-08 22:13:01 +01:00
commit 7b07c57fd5
67 changed files with 20874 additions and 0 deletions

View File

@ -0,0 +1,16 @@
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# For the full list of supported browsers by the Angular framework, please see:
# https://angular.io/guide/browser-support
# You can see what browsers were selected by your queries by running:
# npx browserslist
last 1 Chrome version
last 1 Firefox version
last 2 Edge major versions
last 2 Safari major versions
last 2 iOS major versions
Firefox ESR

View File

@ -0,0 +1,16 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false

42
todo-app/todo-app/.gitignore vendored Normal file
View File

@ -0,0 +1,42 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db

View File

@ -0,0 +1,4 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
"recommendations": ["angular.ng-template"]
}

20
todo-app/todo-app/.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,20 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "ng serve",
"type": "pwa-chrome",
"request": "launch",
"preLaunchTask": "npm: start",
"url": "http://localhost:4200/"
},
{
"name": "ng test",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: test",
"url": "http://localhost:9876/debug.html"
}
]
}

42
todo-app/todo-app/.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,42 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "start",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
},
{
"type": "npm",
"script": "test",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
}
]
}

View File

@ -0,0 +1,27 @@
# TodoApp
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 13.2.2.
## Development server
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.
## Code scaffolding
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`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities.
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page.

View File

@ -0,0 +1,113 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"todo-app": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
},
"@schematics/angular:application": {
"strict": true
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/todo-app",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "todo-app:build:production"
},
"development": {
"browserTarget": "todo-app:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "todo-app:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
"src/styles.scss"
],
"scripts": []
}
}
}
}
},
"defaultProject": "todo-app"
}

View File

@ -0,0 +1,44 @@
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
jasmine: {
// you can add configuration options for Jasmine here
// the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html
// for example, you can disable the random execution with `random: false`
// or set a specific seed with `seed: 4321`
},
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
jasmineHtmlReporter: {
suppressAll: true // removes the duplicated traces
},
coverageReporter: {
dir: require('path').join(__dirname, './coverage/todo-app'),
subdir: '.',
reporters: [
{ type: 'html' },
{ type: 'text-summary' }
]
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};

19395
todo-app/todo-app/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,44 @@
{
"name": "todo-app",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "~13.2.0",
"@angular/cdk": "^13.2.1",
"@angular/common": "~13.2.0",
"@angular/compiler": "~13.2.0",
"@angular/core": "~13.2.0",
"@angular/forms": "~13.2.0",
"@angular/localize": "~13.2.0",
"@angular/material": "^13.2.1",
"@angular/platform-browser": "~13.2.0",
"@angular/platform-browser-dynamic": "~13.2.0",
"@angular/router": "~13.2.0",
"@ng-bootstrap/ng-bootstrap": "^11.0.0",
"bootstrap": "^4.6.0",
"rxjs": "~7.5.0",
"tslib": "^2.3.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "~13.2.2",
"@angular/cli": "~13.2.2",
"@angular/compiler-cli": "~13.2.0",
"@types/jasmine": "~3.10.0",
"@types/node": "^12.11.1",
"jasmine-core": "~4.0.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.1.0",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "~1.7.0",
"typescript": "~4.5.2"
}
}

View File

@ -0,0 +1,15 @@
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth/auth.guard';
const routes: Routes = [
{ path: '', redirectTo: 'user', pathMatch: 'full' },
{ path: 'todo', loadChildren: () => import('./todo/todo.module').then(m => m.TodoModule), canActivate: [AuthGuard] },
{ path: 'user', loadChildren: () => import('./user/user.module').then(m => m.UserModule) }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

View File

@ -0,0 +1 @@
<router-outlet></router-outlet>

View File

@ -0,0 +1,35 @@
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'todo-app'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('todo-app');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('.content span')?.textContent).toContain('todo-app app is running!');
});
});

View File

@ -0,0 +1,10 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'todo-app';
}

View File

@ -0,0 +1,29 @@
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthIntercpetor } from './auth/auth.interceptor';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
NgbModule,
HttpClientModule
],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: AuthIntercpetor,
multi: true
}],
bootstrap: [AppComponent]
})
export class AppModule { }

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { AuthGuard } from './auth.guard';
describe('AuthGuard', () => {
let guard: AuthGuard;
beforeEach(() => {
TestBed.configureTestingModule({});
guard = TestBed.inject(AuthGuard);
});
it('should be created', () => {
expect(guard).toBeTruthy();
});
});

View File

@ -0,0 +1,22 @@
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if (localStorage.getItem('token') !== null) {
return true;
} else {
this.router.navigateByUrl('/user');
}
return false;
}
}

View File

@ -0,0 +1,32 @@
import { Router } from '@angular/router';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";
@Injectable()
export class AuthIntercpetor implements HttpInterceptor {
constructor(private router: Router) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (localStorage.getItem('token') !== null) {
const request = req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('token'))
});
return next.handle(request).pipe(tap(
() => {},
err => {
localStorage.removeItem('token');
localStorage.removeItem('userId');
localStorage.removeItem('userName');
localStorage.removeItem('fullName');
this.router.navigateByUrl('/user');
}
));
} else {
return next.handle(req.clone());
}
}
}

View File

@ -0,0 +1,21 @@
<div class="d-flex justify-content-end">
<a routerLink="/todo/list" class="btn btn-primary mr-5">Back</a>
</div>
<div *ngIf="todoItem; else loadingData">
<div class="d-flex justify-content-center">
<div class="form-wrapper">
<div>
<input [(ngModel)]="todoItem.name" class="form-control mb-2" placeholder="Task name"/>
<textarea [(ngModel)]="todoItem.description" class="form-control mb-2" placeholder="Description"></textarea>
</div>
<div>
<button (click)="onSave()" class="btn btn-primary mr-2">Save</button>
<button *ngIf="!todoItem.done && id" (click)="onDone()" class="btn btn-primary mr-2">Done</button>
<button *ngIf="id" (click)="onDelete()" class="btn btn-danger mr-2">Delete</button>
</div>
</div>
</div>
</div>
<ng-template #loadingData>
Loading data...
</ng-template>

View File

@ -0,0 +1,3 @@
.form-wrapper {
width: 600px;
}

View File

@ -0,0 +1,25 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TodoItemDetailsComponent } from './todo-item-details.component';
describe('TodoItemDetailsComponent', () => {
let component: TodoItemDetailsComponent;
let fixture: ComponentFixture<TodoItemDetailsComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ TodoItemDetailsComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(TodoItemDetailsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,57 @@
import { TodoItemDetailsInterface } from './../../interfaces/todo-item-details.interface';
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { TodoListService } from './../../services/todo-list.service';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-todo-item-details',
templateUrl: './todo-item-details.component.html',
styleUrls: ['./todo-item-details.component.scss']
})
export class TodoItemDetailsComponent implements OnInit {
todoItem: TodoItemDetailsInterface;
constructor(private todoListService: TodoListService,
private activatedRoute: ActivatedRoute,
private router: Router) { }
ngOnInit(): void {
const id = this.activatedRoute.snapshot.params['id'];
if (id) {
this.todoListService.getTodoItemById(id).subscribe(data => {
this.todoItem = data;
});
} else {
this.todoItem = {
name: '',
description: '',
done: false
}
}
}
onSave(): void {
if (this.todoItem.id) {
this.todoListService.putTodoItem(this.todoItem).subscribe(() => {
this.router.navigateByUrl('/todo/list');
});
} else {
this.todoListService.postTodoItem(this.todoItem).subscribe(() => {
this.router.navigateByUrl('/todo/list');
});
}
}
onDelete(): void {
this.todoListService.deleteTodoItem(this.todoItem.id).subscribe(() => {
this.router.navigateByUrl('/todo/list');
});
}
onDone(): void {
this.todoItem.done = true;
this.todoListService.putTodoItem(this.todoItem).subscribe(() => {
this.router.navigateByUrl('/todo/list');
});
}
}

View File

@ -0,0 +1,10 @@
<div class="border rounded p-3 mb-2 todo-item-container">
<div>
<h2>{{name}}</h2>
</div>
<div class="d-flex justify-content-end">
<button class="btn btn-primary mr-2" (click)="onEdit()">Edit</button>
<button *ngIf="!done" (click)="onDone()" class="btn btn-primary mr-2">Done</button>
<button class="btn btn-danger mr-2" (click)="onDelete()">Delete</button>
</div>
</div>

View File

@ -0,0 +1,2 @@
.todo-item-container {
}

View File

@ -0,0 +1,25 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TodoItemComponent } from './todo-item.component';
describe('TodoItemComponent', () => {
let component: TodoItemComponent;
let fixture: ComponentFixture<TodoItemComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ TodoItemComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(TodoItemComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,36 @@
import { Router } from '@angular/router';
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-todo-item',
templateUrl: './todo-item.component.html',
styleUrls: ['./todo-item.component.scss']
})
export class TodoItemComponent implements OnInit {
@Input() name: string;
@Input() id: number;
@Input() done: boolean;
@Output() edit = new EventEmitter<number>();
@Output() delete = new EventEmitter<number>();
@Output() doneChange = new EventEmitter<number>();
constructor() { }
ngOnInit(): void {
}
onEdit(): void {
this.edit.emit(this.id);
}
onDelete(): void {
this.delete.emit(this.id);
}
onDone(): void {
this.doneChange.emit(this.id);
}
}

View File

@ -0,0 +1,25 @@
<div class="row justify-content-center">
<div class="todo-item-list col-4 m-2 p-2 border rounded">
<h2>TODO:</h2>
<app-todo-item *ngFor="let todoItem of todoItemList"
[id]="todoItem.id"
[name]="todoItem.name"
[done]="todoItem.done"
(edit)="onEdit($event)"
(delete)="onDelete($event)"
(doneChange)="onDone($event)"></app-todo-item>
</div>
<div class="done-item-list col-4 m-2 p-2 border rounded">
<h2>DONE:</h2>
<app-todo-item *ngFor="let todoItem of doneItemList"
[id]="todoItem.id"
[name]="todoItem.name"
[done]="todoItem.done"
(edit)="onEdit($event)"
(delete)="onDelete($event)"
(doneChange)="onDone($event)"></app-todo-item>
</div>
<div class="col-12 text-center">
<button class="btn btn-primary" (click)="onAddNew()">Add new</button>
</div>
</div>

View File

@ -0,0 +1,25 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TodoListComponent } from './todo-list.component';
describe('TodoListComponent', () => {
let component: TodoListComponent;
let fixture: ComponentFixture<TodoListComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ TodoListComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(TodoListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,54 @@
import { Router } from '@angular/router';
import { TodoListService } from './../../services/todo-list.service';
import { Component, OnInit } from '@angular/core';
import { TodoListItemInterface } from '../../interfaces/todo-list-item.interface';
@Component({
selector: 'app-todo-list',
templateUrl: './todo-list.component.html',
styleUrls: ['./todo-list.component.scss']
})
export class TodoListComponent implements OnInit {
itemList: TodoListItemInterface[];
todoItemList: TodoListItemInterface[];
doneItemList: TodoListItemInterface[];
constructor(private todoListService: TodoListService,
private router: Router) { }
ngOnInit(): void {
this.getTodoItemList();
}
onAddNew(): void {
this.router.navigateByUrl('/todo/edit');
}
onEdit(id: number): void {
this.router.navigateByUrl('/todo/edit/' + id);
}
onDelete(id: number): void {
this.todoListService.deleteTodoItem(id).subscribe(() => {
this.getTodoItemList();
});
}
onDone(id: number): void {
this.todoListService.getTodoItemById(id).subscribe(data => {
const todoItem = data;
todoItem.done = true;
this.todoListService.putTodoItem(todoItem).subscribe(() => {
this.getTodoItemList();
});
});
}
private getTodoItemList(): void {
this.todoListService.getAllTodoItems().subscribe(data => {
this.todoItemList = data.filter(todoItem => !todoItem.done);
this.doneItemList = data.filter(todoItem => todoItem.done);
});
}
}

View File

@ -0,0 +1,5 @@
import {TodoListItemInterface} from './todo-list-item.interface';
export interface TodoItemDetailsInterface extends TodoListItemInterface {
description: string;
}

View File

@ -0,0 +1,5 @@
export interface TodoListItemInterface {
id?: number;
name: string;
done: boolean;
}

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { TodoListService } from './todo-list.service';
describe('TodoListService', () => {
let service: TodoListService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(TodoListService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@ -0,0 +1,34 @@
import { TodoItemDetailsInterface } from './../interfaces/todo-item-details.interface';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { TodoListItemInterface } from '../interfaces/todo-list-item.interface';
import { environment } from './../../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class TodoListService {
constructor(private http: HttpClient) { }
getAllTodoItems(): Observable<TodoListItemInterface[]> {
return this.http.get<TodoListItemInterface[]>(environment.host + environment.apiEndpoints.todo);
}
getTodoItemById(id: number): Observable<TodoItemDetailsInterface> {
return this.http.get<TodoItemDetailsInterface>(environment.host + environment.apiEndpoints.todo + '/' + id);
}
postTodoItem(todoItem: TodoItemDetailsInterface): Observable<number> {
return this.http.post<number>(environment.host + environment.apiEndpoints.todo, todoItem);
}
putTodoItem(todoItem: TodoItemDetailsInterface): Observable<number> {
return this.http.put<number>(environment.host + environment.apiEndpoints.todo + '/' + todoItem.id, todoItem);
}
deleteTodoItem(id: number): Observable<void> {
return this.http.delete<void>(environment.host + environment.apiEndpoints.todo + '/' + id);
}
}

View File

@ -0,0 +1,37 @@
import { TodoListComponent } from './components/todo-list/todo-list.component';
import { TodoItemDetailsComponent } from './components/todo-item-details/todo-item-details.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BaseComponent } from './../user/components/base/base.component';
const routes: Routes = [
{
path: '',
component: BaseComponent,
children: [
{
path: 'list',
component: TodoListComponent
},
{
path: 'edit',
component: TodoItemDetailsComponent
},
{
path: 'edit/:id',
component: TodoItemDetailsComponent
},
{
path: '',
redirectTo: 'list',
pathMatch: 'full'
}
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class TodoRoutingModule { }

View File

@ -0,0 +1,23 @@
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { FormsModule } from '@angular/forms';
import { TodoListComponent } from './components/todo-list/todo-list.component';
import { TodoItemComponent } from './components/todo-item/todo-item.component';
import { TodoItemDetailsComponent } from './components/todo-item-details/todo-item-details.component';
import { TodoRoutingModule } from './todo-routing.module';
@NgModule({
declarations: [
TodoListComponent,
TodoItemComponent,
TodoItemDetailsComponent
],
imports: [
CommonModule,
TodoRoutingModule,
NgbModule,
FormsModule
]
})
export class TodoModule { }

View File

@ -0,0 +1,9 @@
<div class="row p-3 navbar bg-dark text-white mb-2">
<div class="col-4"></div>
<div class="col-4"><h1 class="text-center">TODO LIST</h1></div>
<div class="col-4 d-flex justify-content-end">
<div class="d-flex justify-content-center flex-column mr-3">{{ userName }} ({{ fullName }})</div>
<button (click)="onLogout()" class="btn btn-primary">Log out</button>
</div>
</div>
<router-outlet></router-outlet>

View File

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { BaseComponent } from './base.component';
describe('BaseComponent', () => {
let component: BaseComponent;
let fixture: ComponentFixture<BaseComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ BaseComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(BaseComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,29 @@
import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-base',
templateUrl: './base.component.html',
styleUrls: ['./base.component.scss']
})
export class BaseComponent implements OnInit {
userName: string;
fullName: string;
constructor(private router: Router) { }
ngOnInit(): void {
this.userName = localStorage.getItem('userName');
this.fullName = localStorage.getItem('fullName');
}
onLogout(): void {
localStorage.setItem('token', '');
localStorage.setItem('userId', '');
localStorage.setItem('userName', '');
localStorage.setItem('fullName', '');
this.router.navigateByUrl('/');
}
}

View File

@ -0,0 +1,22 @@
<h1 class="text-center">TODO LIST</h1>
<div class="login-form-container d-flex justify-content-center">
<div class="d-flex flex-column">
<form [formGroup]="loginForm" class="login-form d-flex flex-column mt-5">
<mat-form-field>
<mat-label>Username</mat-label>
<input matInput formControlName="userName" />
</mat-form-field>
<mat-form-field>
<mat-label>Password</mat-label>
<input matInput formControlName="password" type="password" />
</mat-form-field>
<div class="mt-4">
<button (click)="onLoginUser()" class="btn btn-primary">Sign in</button>
</div>
</form>
<a routerLink="/user/register">Registration</a>
</div>
</div>

View File

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { LoginComponent } from './login.component';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,43 @@
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { UserService } from '../../services/user.service';
import { Auth } from '../../interfaces/auth.interface';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
constructor(private userSerice: UserService,
private router: Router) { }
ngOnInit(): void {
this.loginForm = this.createLoginForm();
}
createLoginForm(): FormGroup {
return new FormGroup({
userName: new FormControl('', Validators.required),
fullName: new FormControl('', Validators.required),
password: new FormControl('', Validators.required),
repeatedPassword: new FormControl('', Validators.required)
});
}
onLoginUser(): void {
this.userSerice.login(this.loginForm.value).subscribe((auth: Auth) => {
localStorage.setItem('token', auth.token);
localStorage.setItem('userId', auth.user.id);
localStorage.setItem('userName', auth.user.userName);
localStorage.setItem('fullName', auth.user.fullName);
this.router.navigateByUrl('/todo');
});
}
}

View File

@ -0,0 +1,43 @@
<h1 class="text-center">TODO LIST</h1>
<div class="register-form-container d-flex justify-content-center">
<div class="d-flex flex-column">
<form [formGroup]="registerForm" class="register-form d-flex flex-column mt-5">
<mat-form-field>
<mat-label>Username</mat-label>
<input matInput formControlName="userName" />
</mat-form-field>
<mat-form-field>
<mat-label>Full name</mat-label>
<input matInput formControlName="fullName" />
</mat-form-field>
<div formGroupName="passwordForm" class="d-flex flex-column">
<mat-form-field>
<mat-label>Password</mat-label>
<input matInput formControlName="password" type="password" />
</mat-form-field>
<mat-form-field>
<mat-label>Repeated password</mat-label>
<input matInput formControlName="repeatedPassword" type="password" />
</mat-form-field>
<div style="color:#ff7355" *ngIf="registerForm.get(['passwordForm', 'password']).value != registerForm.get(['passwordForm', 'repeatedPassword']).value && registerForm.get(['passwordForm', 'repeatedPassword']).value != null">
Password does not match
</div>
</div>
<div class="mt-4">
<button [disabled]="registerForm.invalid"
(click)="onRegisterUser()"
class="btn btn-primary">
Sign up
</button>
</div>
</form>
<a routerLink="/">Back to login page</a>
</div>
</div>

View File

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RegisterComponent } from './register.component';
describe('RegisterComponent', () => {
let component: RegisterComponent;
let fixture: ComponentFixture<RegisterComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ RegisterComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(RegisterComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,52 @@
import { UserService } from './../../services/user.service';
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, AbstractControl } from '@angular/forms';
import { Router } from '@angular/router';
import { User } from '../../interfaces/user.interface';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
registerForm: FormGroup;
constructor(private userSerice: UserService,
private router: Router) { }
ngOnInit(): void {
this.registerForm = this.createRegisterForm();
}
createRegisterForm(): FormGroup {
return new FormGroup({
userName: new FormControl('', Validators.required),
fullName: new FormControl('', Validators.required),
passwordForm: new FormGroup({
password: new FormControl('', Validators.required),
repeatedPassword: new FormControl('', Validators.required)
}, this.passwordValidator)
});
}
private passwordValidator(form: AbstractControl): { invalid: boolean } {
if (form.get('password').value !== form.get('repeatedPassword').value) {
return {invalid: true};
}
}
onRegisterUser(): void {
const user: User = {
userName: this.registerForm.get('userName').value,
fullName: this.registerForm.get('fullName').value,
password: this.registerForm.get(['passwordForm', 'password']).value
};
this.userSerice.register(user).subscribe(() => {
this.router.navigateByUrl('/user/login');
});
}
}

View File

@ -0,0 +1,5 @@
import { User } from './user.interface';
export interface Auth {
token: string;
user: User;
}

View File

@ -0,0 +1,6 @@
export interface User {
id?: string;
userName: string;
fullName: string;
password?: string;
}

View File

@ -0,0 +1,23 @@
import { environment } from './../../../environments/environment';
import { User } from './../interfaces/user.interface';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Auth } from '../interfaces/auth.interface';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) { }
register(user: User): Observable<void> {
return this.http.post<void>(environment.host + environment.apiEndpoints.users.register, user);
}
login(user: User): Observable<Auth> {
return this.http.post<Auth>(environment.host + environment.apiEndpoints.users.login, user);
}
}

View File

@ -0,0 +1,17 @@
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './components/login/login.component';
import { RegisterComponent } from './components/register/register.component';
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full'},
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class UserRoutingModule { }

View File

@ -0,0 +1,26 @@
import { MatInputModule } from '@angular/material/input';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RegisterComponent } from './components/register/register.component';
import { LoginComponent } from './components/login/login.component';
import { ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { UserRoutingModule } from './user-routing.module';
import { BaseComponent } from './components/base/base.component';
@NgModule({
declarations: [RegisterComponent, LoginComponent, BaseComponent],
imports: [
CommonModule,
ReactiveFormsModule,
MatFormFieldModule,
MatInputModule,
UserRoutingModule
],
exports: [
BaseComponent
]
})
export class UserModule { }

View File

View File

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

View File

@ -0,0 +1,11 @@
export const environment = {
production: false,
host: 'http://localhost:59909/',
apiEndpoints: {
todo: 'api/todo',
users: {
login: 'api/users/login',
register: 'api/users/register'
}
}
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 948 B

View File

@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>TodoApp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body class="mat-typography">
<app-root></app-root>
</body>
</html>

View File

@ -0,0 +1,12 @@
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));

View File

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

View File

@ -0,0 +1,7 @@
/* You can add global styles to this file, and also import other style files */
html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }
/* Importing Bootstrap SCSS file. */
@import '~bootstrap/scss/bootstrap';

View File

@ -0,0 +1,26 @@
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
declare const require: {
context(path: string, deep?: boolean, filter?: RegExp): {
<T>(id: string): T;
keys(): string[];
};
};
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting(),
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);

View File

@ -0,0 +1,15 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}

View File

@ -0,0 +1,33 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": false,
"strict": false,
"noImplicitOverride": false,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": false,
"noFallthroughCasesInSwitch": true,
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"strictPropertyInitialization": false,
"moduleResolution": "node",
"importHelpers": true,
"target": "es2017",
"module": "es2020",
"lib": [
"es2020",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": false,
"strictInputAccessModifiers": false,
"strictTemplates": false
}
}

View File

@ -0,0 +1,18 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"files": [
"src/test.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}