Commit 5fe285f2 authored by shyam sathali's avatar shyam sathali

project files uploaded..

parent ca8898e9
# 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
not IE 11 # Angular supports IE 11 only as an opt-in. To opt-in, remove the 'not' prefix on this line.
# 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
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist
/tmp
/out-tsc
# Only exists if Bazel was run
/bazel-out
# dependencies
/node_modules
# profiling files
chrome-profiler-events*.json
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
yarn-error.log
testem.log
/typings
# System Files
.DS_Store
Thumbs.db
# Angular # ToDos
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 12.0.3.
## 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.
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"cli": {
"analytics": false
},
"version": 1,
"newProjectRoot": "projects",
"projects": {
"to-dos": {
"projectType": "application",
"schematics": {
"@schematics/angular:application": {
"strict": true
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/to-dos",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css",
"./node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"./node_modules/bootstrap/dist/js/bootstrap.min.js"
]
},
"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": "to-dos:build:production"
},
"development": {
"browserTarget": "to-dos:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "to-dos: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",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
}
}
}
}
},
"defaultProject": "to-dos"
}
// 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/to-dos'),
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
});
};
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "to-dos",
"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": "~12.0.3",
"@angular/common": "~12.0.3",
"@angular/compiler": "~12.0.3",
"@angular/core": "~12.0.3",
"@angular/forms": "~12.0.3",
"@angular/platform-browser": "~12.0.3",
"@angular/platform-browser-dynamic": "~12.0.3",
"@angular/router": "~12.0.3",
"bootstrap": "^5.0.0-beta3",
"rxjs": "~6.6.0",
"tslib": "^2.1.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "~12.0.3",
"@angular/cli": "~12.0.3",
"@angular/compiler-cli": "~12.0.3",
"@types/jasmine": "~3.6.0",
"@types/node": "^12.11.1",
"jasmine-core": "~3.7.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"typescript": "~4.2.3"
}
}
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthenticationComponent } from './authentication/authentication.component';
import { TodoFormComponent } from './todo-form/todo-form.component';
const routes: Routes = [
{path:"", component:TodoFormComponent},
{path:"auth", component:AuthenticationComponent},
{path:":id/edit", component:TodoFormComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
strong{
font-weight: bold;
font-size: 2.4rem;
color: blueviolet;
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
}
\ No newline at end of file
<div class="container">
<div class="row">
<div class="col-xs-12">
<strong>Todo App</strong>
<div class="row">
<div class="col-md-6">
<router-outlet></router-outlet>
</div>
<div class="col-md-6" *ngIf="isLogin">
<b style="color: rgb(187, 20, 187); font-size: 20px;">All Todos</b>
<app-todos></app-todos>
</div>
</div>
</div>
</div>
</div>
\ No newline at end of file
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 'to-dos'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('to-dos');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement;
expect(compiled.querySelector('.content span').textContent).toContain('to-dos app is running!');
});
});
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { AuthService } from './authentication/auth.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, OnDestroy{
isLoginSub! : Subscription;
isLogin:boolean = false;
constructor(private authService:AuthService, private router:Router){}
ngOnInit(): void {
this.isLoginSub = this.authService.isLogin.subscribe(isLogin=>{
this.isLogin = isLogin;
console.log(`islogin is: ${isLogin}`);
if(!this.isLogin){
this.router.navigate(["auth"])
}else{
this.router.navigate([""])
}
})
if(!this.isLogin){
this.authService.logout();
}
}
title = 'to-dos';
ngOnDestroy(){
this.isLoginSub.unsubscribe();
}
}
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule} from '@angular/common/http'
import { AppComponent } from './app.component';
import { TodoFormComponent } from './todo-form/todo-form.component';
import { TodosComponent } from './todos/todos.component';
import { LoadingRipleComponent } from './centraldata/loading-indicator/loading-riple.component';
import { AuthenticationComponent } from './authentication/authentication.component';
import { AppRoutingModule } from './app-routing.module';
@NgModule({
declarations: [
AppComponent,
TodoFormComponent,
TodosComponent,
LoadingRipleComponent,
AuthenticationComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Subject } from "rxjs";
@Injectable({providedIn:"root"})
export class AuthService{
constructor(private http:HttpClient){}
isLogin : Subject<boolean> = new Subject<boolean>();
login(user:User){
return this.http.post<AuthResponseData>("http://localhost:3000/api/auth/login",user);
}
register(user:User){
return this.http.post<AuthResponseData>("http://localhost:3000/api/auth/register",user);
}
autoLogin(){
let token = localStorage.getItem('token');
if(token){
this.isLogin.next(true)
}else{
this.isLogin.next(false);
}
}
logout(){
console.log("logout");
localStorage.removeItem('token');
this.isLogin.next(false);
}
}
export interface User{
username?:string,
email:String,
password:String
}
export interface AuthResponseData{
message:string,
success:boolean,
token?:string,
data?: User
}
\ No newline at end of file
input.ng-invalid.ng-touched{
border: 2px solid orangered;
}
span{
color: orangered;
}
\ No newline at end of file
<div class="row mt-5">
<div class="col-xs-12">
<div class="border-right-2">
<form #authForm="ngForm" (ngSubmit)="onSubmit()">
<div class="row" *ngIf="!isLoginMode">
<div class="col-xs-5">
<div class="form-group">
<label for="username"> <strong>Username</strong> </label>
<input type="text" class="form-control" id="username" required name="username" ngModel #username="ngModel">
<span *ngIf="username.invalid && username.touched">Please enter your username</span>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-5">
<div class="form-group">
<label for="email"> <strong>Email</strong> </label>
<input type="email" class="form-control" id="email" required name="email" ngModel #email="ngModel">
<span *ngIf="email.invalid && email.touched">Please enter your email</span>
</div>
</div>
</div>
<div class="row mt-2">
<div class="col-xs-12">
<div class="form-group">
<label for="password"> <strong>password</strong> </label>
<input type="password" class="form-control" id="password" required name="password" ngModel #password="ngModel" [minlength]="6" >
<span *ngIf="password.invalid && password.touched">Please enter your password</span>
</div>
</div>
</div>
<div class="row mt-5">
<div class="form-group">
<button class="btn btn-primary" type="submit" [disabled]="authForm.invalid"> {{isLoginMode ? "Login" : "Sign Up"}} </button>
<button class="btn btn-danger mx-3" type="button" (click)= "switchMode()">Swith to {{isLoginMode ? "Sign Up" : "Login"}} </button>
</div>
</div>
</form>
</div>
</div>
</div>
\ No newline at end of file
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AuthenticationComponent } from './authentication.component';
describe('AuthenticationComponent', () => {
let component: AuthenticationComponent;
let fixture: ComponentFixture<AuthenticationComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ AuthenticationComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(AuthenticationComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { AuthService } from './auth.service';
@Component({
selector: 'app-authentication',
templateUrl: './authentication.component.html',
styleUrls: ['./authentication.component.css']
})
export class AuthenticationComponent implements OnInit {
@ViewChild('authForm') authForm!:NgForm;
constructor(private authService:AuthService) { }
isLoginMode = true;
ngOnInit(): void {
}
onSubmit(){
// console.log(`IsLogin ${this.isLoginMode}`);
// console.log(this.authForm.value);
//this.authService.isLogin.next(true);
if(this.isLoginMode){
this.authService.login(this.authForm.value).subscribe(responseData=>{
console.log(responseData);
if(responseData.success){
this.authService.isLogin.next(true);
localStorage.setItem('token',responseData.token!)
}else{
console.log(responseData.message);
}
});
}else{
this.isLoginMode=true;
this.authService.register(this.authForm.value).subscribe(responseData=>{
console.log(responseData);
if(responseData.success){
this.authService.isLogin.next(true);
localStorage.setItem('token',responseData.token!)
}else{
console.log(responseData.message);
}
});
}
}
switchMode(){
this.isLoginMode = !this.isLoginMode
}
}
import { HttpClient, HttpParams } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { ResponseData, Todo } from "../todo.service";
@Injectable({providedIn:'root'})
export class DataStoreService{
constructor(private http:HttpClient){}
// saveData(todos:Todo[]){
// this.http.put("https://angulardemo-3a75a-default-rtdb.firebaseio.com/todos.json", todos).subscribe(respData=>{
// console.log(respData);
// })
// }
// fetchData(){
// return this.http.get("https://angulardemo-3a75a-default-rtdb.firebaseio.com/todos.json");
// }
saveTodo(todo:Todo){
return this.http.post<ResponseData>("http://localhost:3000/api/todos/save",todo);
};
fetchAllTodos(){
return this.http.get<ResponseData>("http://localhost:3000/api/todos/all");
}
deleteTodo(id:string){
return this.http.delete<ResponseData>("http://localhost:3000/api/todos/delete/"+id);
}
updateTodo(id:string, updatedTodo:Todo){
return this.http.put<ResponseData>("http://localhost:3000/api/todos/update/"+id, updatedTodo);
}
}
\ No newline at end of file
@keyframes ldio-v8era3rmin {
0% {
top: 112.80000000000001px;
left: 112.80000000000001px;
width: 0;
height: 0;
opacity: 1;
}
100% {
top: 21.150000000000002px;
left: 21.150000000000002px;
width: 183.3px;
height: 183.3px;
opacity: 0;
}
}.ldio-v8era3rmin div {
position: absolute;
border-width: 4.7px;
border-style: solid;
opacity: 1;
border-radius: 50%;
animation: ldio-v8era3rmin 1.7857142857142856s cubic-bezier(0,0.2,0.8,1) infinite;
}.ldio-v8era3rmin div:nth-child(1) {
border-color: #e90c59;
animation-delay: 0s;
}
.ldio-v8era3rmin div:nth-child(2) {
border-color: #46dff0;
animation-delay: -0.8928571428571428s;
}
.loadingio-spinner-ripple-6k4r25kx7t {
width: 235px;
height: 235px;
display: inline-block;
overflow: hidden;
background: #ffffff;
}
.ldio-v8era3rmin {
width: 100%;
height: 100%;
position: relative;
transform: translateZ(0) scale(1);
backface-visibility: hidden;
transform-origin: 0 0; /* see note above */
}
.ldio-v8era3rmin div { box-sizing: content-box; }
/* generated by https://loading.io/ */
\ No newline at end of file
import { Component } from "@angular/core";
@Component({
selector:'app-loading',
template:`<div class="loadingio-spinner-ripple-6k4r25kx7t"><div class="ldio-v8era3rmin">
<div></div><div></div>
</div></div>`,
styleUrls:['./loading-riple.component.css']
})
export class LoadingRipleComponent{
}
\ No newline at end of file
label{
font-size: 18px;
font-weight: bold;
}
label.radioBtn{
font-size: 14px;
font-weight: bold;
}
input.ng-invalid.ng-touched{
border: 2px solid orangered;
}
span{
color: orangered;
}
\ No newline at end of file
<div class="row mt-5">
<div class="col-xs-12">
<div class="border-right-2">
<form #todoForm="ngForm" (ngSubmit)="onSubmit()">
<div class="row">
<div class="col-xs-5">
<div class="form-group">
<label for="title">Todo Title</label>
<input type="text" class="form-control" id="title" required name="title" ngModel #title="ngModel">
<span *ngIf="title.invalid && title.touched">this field is required</span>
</div>
</div>
</div>
<div class="row mt-2">
<div class="col-xs-12">
<div class="form-group">
<label for="todo">Todo Text</label>
<input type="text" class="form-control" id="todo" required name="text" ngModel #text="ngModel">
<span *ngIf="text.invalid && text.touched">this field is required</span>
</div>
</div>
</div>
<div class="row mt-2">
<div class="col-xs-12">
<strong style="font-size: 18px;">Todo Status</strong>
<div class="form-group mt-2">
<div class="form-check" *ngFor="let todoStatus of todoStatuses" id="radiobtn">
<label class="radioBtn" for="status"><input class="form-check-input" type="radio" name="status" [value]="todoStatus" id="status" [ngModel]="defaultStatus"> {{todoStatus}} </label>
</div>
</div>
</div>
</div>
<div class="row mt-5">
<div class="form-group">
<button class="btn btn-primary" type="submit" [disabled]="todoForm.invalid"> {{buttonName}} </button>
<button class="btn btn-danger mx-3" *ngIf="isUpdate" type="button" (click)="onCancel()">Cancel</button>
</div>
</div>
<div class="mt-5">
<button class="btn btn-danger" (click)="logout()">Logout</button>
</div>
</form>
</div>
</div>
</div>
\ No newline at end of file
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TodoFormComponent } from './todo-form.component';
describe('TodoFormComponent', () => {
let component: TodoFormComponent;
let fixture: ComponentFixture<TodoFormComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ TodoFormComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(TodoFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';
import { AuthService } from '../authentication/auth.service';
import { Todo, TodoService } from '../todo.service';
@Component({
selector: 'app-todo-form',
templateUrl: './todo-form.component.html',
styleUrls: ['./todo-form.component.css']
})
export class TodoFormComponent implements OnInit, OnDestroy {
@ViewChild("todoForm") todoForm:NgForm | undefined;
todoStatuses:string[] = ['pending', 'completed'];
defaultStatus="pending";
formValuesSubscription!: Subscription;
buttonName:string = "Add Todo";
isUpdate:boolean = false;
updatingItemIndex!:number;
constructor(private todoService:TodoService, private authService:AuthService, private route:ActivatedRoute) { }
ngOnInit(): void {
this.formValuesSubscription = this.todoService.seletedItem.subscribe((todo:Todo)=>{
this.todoForm?.setValue({
title:todo.title,
text:todo.text,
status:todo.status
})
});
this.todoService.isUpdate.subscribe((isUpdate)=>{
this.buttonName = isUpdate.isUpdating?"Update Todo":"Add Todo";
this.isUpdate = isUpdate.isUpdating;
this.updatingItemIndex = isUpdate.id
});
}
onSubmit(){
//console.log(this.todoForm);
if(this.isUpdate){
//console.log("updating item index: "+this.updatingItemIndex);
this.todoService.updateTodo(this.updatingItemIndex,{title:this.todoForm?.value.title,text:this.todoForm?.value.text, status:this.todoForm?.value.status})
this.formReset();
}else{
this.todoService.addTodo({title:this.todoForm?.value.title,text:this.todoForm?.value.text, status:this.todoForm?.value.status})
this.formReset();
}
}
onCancel(){
this.formReset();
this.todoService.isUpdate.next({isUpdating:false,id:null})
}
formReset(){
this.todoForm?.reset({
status:this.defaultStatus
})
}
logout(){
this.authService.logout();
}
ngOnDestroy(){
this.formValuesSubscription.unsubscribe();
}
}
import { TestBed } from '@angular/core/testing';
import { TodoService } from './todo.service';
describe('TodoService', () => {
let service: TodoService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(TodoService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { DataStoreService } from './centraldata/data-store.service';
@Injectable({
providedIn: 'root'
})
export class TodoService {
isUpdate:Subject<{isUpdating:boolean,id:any}> = new Subject<{isUpdating:boolean,id:any}>();
latestTodos:Subject<Todo[]>= new Subject<Todo[]>();
seletedItem:Subject<Todo> = new Subject<Todo>();
isLoading:Subject<boolean> = new Subject<boolean>();
todos:Todo[]=[];//[{title:'milk',text:'buy milk',status:'pending'},{title:'eggs',text:'buy eggs',status:'pending'},{title:'workout',text:'Do exercise',status:'completed'}];
constructor(private dataStoreService:DataStoreService) { }
getTodos(){
this.isLoading.next(false);
// this.dataStoreService.fetchData().subscribe(respData=>{
// this.isLoading.next(false);
// this.todos = respData as Todo[];
// this.latestTodos.next(this.todos.slice());
// })
this.dataStoreService.fetchAllTodos().subscribe((responseData:ResponseData)=>{
if(responseData.success){
this.todos = responseData.data as Todo[];
this.latestTodos.next(this.todos.slice());
}else{
console.log(responseData.message);
}
this.isLoading.next(false);
})
return this.todos.slice();
}
getTodo(index:number){
return this.todos.slice()[index];
}
addTodo(newTodo:Todo){
this.isLoading.next(true);
// this.todos.push(newTodo);
// this.latestTodos.next(this.todos.slice());
// this.isLoading.next(false);
this.dataStoreService.saveTodo(newTodo).subscribe((responseData:ResponseData)=>{
console.log(responseData.data as Todo);
this.todos.push(responseData.data as Todo);
this.latestTodos.next(this.todos.slice());
this.isLoading.next(false);
});
}
updateTodo(i:number,updateTodo:Todo){
this.todos[i] = {_id:this.todos[i]._id!,title:updateTodo.title, text:updateTodo.text, status:updateTodo.status};
this.isUpdate.next({isUpdating:false,id:null});
// this.dataStoreService.saveData(this.todos);
let id = this.todos[i]._id!;
this.dataStoreService.updateTodo(id,updateTodo).subscribe((responseData:ResponseData)=>{
if(responseData.success){
console.log(responseData.message);
}else{
console.log(responseData.message);
}
this.latestTodos.next(this.todos.slice());
})
}
onSeletedItem(todo:Todo){
console.log("Id is: "+this.todos.indexOf(todo));
this.isUpdate.next({isUpdating:true,id:this.todos.indexOf(todo)});
this.seletedItem.next(todo);
}
deleteTodo(i:number){
console.log("deleted id:"+i);
console.log(this.todos[i]);
let id = this.todos[i]._id!;
console.log(`ID is: ${id}`);
this.todos.splice(i,1);
// this.dataStoreService.saveData(this.todos);
this.dataStoreService.deleteTodo(id).subscribe((responseData:ResponseData)=>{
console.log(responseData.message);
this.latestTodos.next(this.todos.slice());
});
}
}
export interface Todo{
_id?:string,
title:string,
text:string,
status:string
}
export interface ResponseData{
message:string,
success:boolean,
data:Todo | Todo[]
}
i.pending{
color: orangered;
}
i.completed{
color: green;
}
p.completed{
font-size: 18px;
text-decoration: line-through;
text-decoration-thickness: 4px;
}
div.hightLight{
background-color: lightskyblue;
}
\ No newline at end of file
<div class="row">
<div class="col-xs-12">
<div style="text-align: center;">
<app-loading *ngIf="isLoading"></app-loading>
</div>
<div *ngFor="let todo of todos; let i=index">
<div [class]="i===itemIndex?'hightLight':''" class="list-group-item clearfix m-2 rounded-2 border-dark">
<div (click)="onSelect(i)">
<strong class="list-group-item-heading clearfix"> {{todo.title}} </strong>
<p class="list-group-item-text {{todo.status}}"> {{todo.text}} </p>
<i [class]="todo.status"> {{todo.status}} </i>
</div>
<div style="text-align: right;">
<button class="btn btn-danger" type="button" (click)="onDelete(i)">Delete</button>
</div>
</div>
</div>
<!-- <a class="list-group-item clearfix">
<div>
<strong class="list-group-item-heading">Title</strong>
<p class="list-group-item-text">Text</p>
</div>
</a>
<a>
<div class="list-group-item clearfix">
<strong class="list-group-item-heading">Title</strong>
<p class="list-group-item-text">Text</p>
</div>
</a> -->
</div>
</div>
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TodosComponent } from './todos.component';
describe('TodosComponent', () => {
let component: TodosComponent;
let fixture: ComponentFixture<TodosComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ TodosComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(TodosComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { Todo, TodoService } from '../todo.service';
@Component({
selector: 'app-todos',
templateUrl: './todos.component.html',
styleUrls: ['./todos.component.css']
})
export class TodosComponent implements OnInit, OnDestroy {
todos:Todo[] = [];
todosSubscription : Subscription | undefined;
itemIndex!:number;
itemIndexSubscription!:Subscription;
isLoading:boolean = true;
isLoadingSubscription!:Subscription;
constructor(private todoService:TodoService, private router:Router, private route:ActivatedRoute) { }
ngOnInit(): void {
//this.todos=this.todoService.getTodos();
this.isLoading = this.todos.length!==0;
this.todosSubscription = this.todoService.latestTodos.subscribe((todos:Todo[])=>{
this.todos = todos;
})
this.itemIndexSubscription = this.todoService.isUpdate.subscribe(isUpdate=>{
this.itemIndex = isUpdate.id;
})
this.isLoadingSubscription = this.todoService.isLoading.subscribe(isloading=>{
this.isLoading = isloading;
console.log(`loading : ${isloading}`);
})
}
onSelect(i:number){
// console.log(this.todos[i]);
this.todoService.onSeletedItem(this.todos[i]);
this.itemIndex = i;
}
onDelete(i:number){
this.todoService.deleteTodo(i);
}
ngOnDestroy(){
this.todosSubscription?.unsubscribe();
this.itemIndexSubscription.unsubscribe();
}
}
export const environment = {
production: true
};
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/plugins/zone-error'; // Included with Angular CLI.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ToDos</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
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));
/**
* 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 Safari >= 10, Chrome >= 55 (including Opera),
* Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
*
* Learn more in https://angular.io/guide/browser-support
*/
/***************************************************************************************************
* BROWSER POLYFILLS
*/
/**
* IE11 requires the following for NgClass support on SVG elements
*/
// import 'classlist.js'; // Run `npm install --save classlist.js`.
/**
* Web Animations `@angular/platform-browser/animations`
* Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
* Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
*/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
/**
* 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
*/
/* You can add global styles to this file, and also import other style files */
// 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): {
keys(): string[];
<T>(id: string): T;
};
};
// 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);
/* 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"
]
}
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "es2017",
"module": "es2020",
"lib": [
"es2018",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
/* 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"
]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment