FOLDER DATA
---------------------------------------------------------------------
---------------------------------------------------------------------
data.json
{
"Books": [
{
"id": 1,
"title": "dddddddddddddd",
"price": 5222222222,
"hauter": "shhhhhhhhh"
},
{
"id": "01aa",
"title": "frfr'f",
"price": 444444444,
"hauter": "hyuh"
}
]
}
---------------------------------------------------------------------
---------------------------------------------------------------------
FOLDER SRC
---------------------------------------------------------------------
---------------------------------------------------------------------
main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));
---------------------------------------------------------------------
server.ts
import {
AngularNodeAppEngine,
createNodeRequestHandler,
isMainModule,
writeResponseToNodeResponse,
} from '@angular/ssr/node';
import express from 'express';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const serverDistFolder = dirname(fileURLToPath(import.meta.url));
const browserDistFolder = resolve(serverDistFolder, '../browser');
const app = express();
const angularApp = new AngularNodeAppEngine();
/**
* Example Express Rest API endpoints can be defined here.
* Uncomment and define endpoints as necessary.
*
* Example:
* ```ts
* app.get('/api/**', (req, res) => {
* // Handle API request
* });
* ```
*/
/**
* Serve static files from /browser
*/
app.use(
express.static(browserDistFolder, {
maxAge: '1y',
index: false,
redirect: false,
}),
);
/**
* Handle all other requests by rendering the Angular application.
*/
app.use('/**', (req, res, next) => {
angularApp
.handle(req)
.then((response) =>
response ? writeResponseToNodeResponse(response, res) : next(),
)
.catch(next);
});
/**
* Start the server if this module is the main entry point.
* The server listens on the port defined by the `PORT` environment variable, or defaults to 4000.
*/
if (isMainModule(import.meta.url)) {
const port = process.env['PORT'] || 4000;
app.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
/**
* The request handler used by the Angular CLI (dev-server and during build).
*/
export const reqHandler = createNodeRequestHandler(app);
---------------------------------------------------------------------
main.server.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { config } from './app/app.config.server';
const bootstrap = () => bootstrapApplication(AppComponent, config);
export default bootstrap;
---------------------------------------------------------------------
styles.css
@import url(../node_modules/bootstrap/dist/css/bootstrap.min.css);
---------------------------------------------------------------------
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ExamAngular</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>
---------------------------------------------------------------------
---------------------------------------------------------------------
FOLDER SRC/APP
---------------------------------------------------------------------
---------------------------------------------------------------------
app.routes.server.ts
import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{
path: '**',
renderMode: RenderMode.Prerender
}
];
---------------------------------------------------------------------
app.component.html
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" routerLink="/">All Books</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="/addBook" >Add Book</a>
</li>
</ul>
</div>
</nav>
<router-outlet />
---------------------------------------------------------------------
app.component.spec.ts
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have the 'exam-angular' title`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('exam-angular');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Hello, exam-angular');
});
});
---------------------------------------------------------------------
book.ts
export interface Book{
id:number,
title:string,
price:number,
hauter:string
}
---------------------------------------------------------------------
app.routes.ts
import { Component } from '@angular/core';
import { Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { AddBookComponent } from './addBook/add-book/add-book.component';
import { AllBooksComponent } from './allBooks/all-books/all-books.component';
export const routes: Routes = [
{
path: '',
component: AllBooksComponent,
},
{
path: 'addBook',
component: AddBookComponent,
},
];
---------------------------------------------------------------------
app.config.server.ts
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';
const serverConfig: ApplicationConfig = {
providers: [
provideServerRendering()
// Add other providers as required for your server-side rendering setup
]
};
export const config = mergeApplicationConfig(appConfig, serverConfig);
---------------------------------------------------------------------
app.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import {
provideClientHydration,
withEventReplay,
} from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideClientHydration(withEventReplay()),
provideHttpClient(),
],
};
---------------------------------------------------------------------
app.component.ts
import { Component, OnInit } from '@angular/core';
import { RouterModule, RouterOutlet } from '@angular/router';
import { BookService } from './services/book.service';
@Component({
selector: 'app-root',
imports: [RouterOutlet ,RouterModule ],
templateUrl: './app.component.html',
styleUrl: './app.component.css',
standalone: true
})
export class AppComponent {
title = 'exam-angular';
}
---------------------------------------------------------------------
app.compenent.css (file khawi)
---------------------------------------------------------------------
---------------------------------------------------------------------
---------------------------------------------------------------------
FOLDER src\app\addBook\add-book
---------------------------------------------------------------------
---------------------------------------------------------------------
add-book.component.ts
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { Router, RouterModule } from '@angular/router';
import { BookService } from '../../services/book.service';
@Component({
selector: 'app-add-book',
imports: [ReactiveFormsModule, RouterModule],
templateUrl: './add-book.component.html',
styleUrls: ['./add-book.component.css'],
standalone: true
})
export class AddBookComponent {
formGroup: FormGroup;
constructor(private bookService: BookService, private router: Router) {
this.formGroup = new FormGroup({
title: new FormControl('', Validators.required),
price: new FormControl('', [Validators.required, Validators.min(0)]),
hauter: new FormControl('', Validators.required),
});
}
public add() {
this.bookService.add(this.formGroup.value).subscribe(() => {
this.router.navigate(['/']); // Navigate after successful addition
});
}
}
---------------------------------------------------------------------
add-book.component.html
<form [formGroup]="formGroup">
<div class="form-group">
<label for="title">Title</label>
<input
formControlName="title"
type="text"
class="form-control"
id="title"
aria-describedby="emailHelp"
placeholder="Title"
/>
</div>
<div class="form-group">
<label for="price">Price</label>
<input
formControlName="price"
type="number"
class="form-control"
id="price"
aria-describedby="emailHelp"
placeholder="Price"
/>
</div>
<div class="form-group">
<label for="hauter">Hauter</label>
<input
formControlName="hauter"
type="text"
class="form-control"
id="hauter"
aria-describedby="emailHelp"
placeholder="Hauter"
/>
</div>
<button type="submit" (click)="add()" class="btn btn-primary">Add</button>
</form>
---------------------------------------------------------------------
add-book.component.css (file khawi)
---------------------------------------------------------------------
---------------------------------------------------------------------
---------------------------------------------------------------------
FOLDER src\app\allBooks\all-books
---------------------------------------------------------------------
---------------------------------------------------------------------
all-books.component.html
<table class="table">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">Title</th>
<th scope="col">Price</th>
<th scope="col">Hauter</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let book of books">
<th scope="row">{{book.id}}</th>
<td>{{book.title}}</td>
<td>{{book.price}}</td>
<td>{{book.hauter}}</td>
<td><button class="btn btn-danger" (click)="delete(book.id)">Delete</button>
<button class="btn btn-success" (click)="showFormUpdate(book)">Update</button>
</td>
</tr>
</tbody>
</table>
<form *ngIf="showForm" [formGroup]="formGroup" >
<div class="form-group">
<label for="title">ID</label>
<input
formControlName="id"
type="text"
class="form-control"
id="id"
aria-describedby="emailHelp"
placeholder="Title"
[disabled]="true"
/>
</div>
<div class="form-group">
<label for="title">Title</label>
<input
formControlName="title"
type="text"
class="form-control"
id="title"
aria-describedby="emailHelp"
placeholder="Title"
/>
</div>
<div class="form-group">
<label for="price">Price</label>
<input
formControlName="price"
type="number"
class="form-control"
id="price"
aria-describedby="emailHelp"
placeholder="Price"
/>
</div>
<div class="form-group">
<label for="hauter">Hauter</label>
<input
formControlName="hauter"
type="text"
class="form-control"
id="hauter"
aria-describedby="emailHelp"
placeholder="Hauter"
/>
</div>
<button type="submit" (click)="update()" class="btn btn-primary">update</button>
</form>
----------------------------------------------------------------------------------------------------------------------
all-books.component.ts
import { Component, OnInit } from '@angular/core';
import { Book } from '../../book';
import { BookService } from '../../services/book.service';
import { CommonModule } from '@angular/common';
import { Router } from 'express';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-all-books',
imports: [CommonModule, ReactiveFormsModule],
templateUrl: './all-books.component.html',
styleUrl: './all-books.component.css',
standalone: true
})
export class AllBooksComponent implements OnInit {
books: Book[] = [];
showForm: boolean = false;
formGroup!: FormGroup;
constructor(
private bookService: BookService,
private bookSerive: BookService
) {
this.formGroup = new FormGroup({
id:new FormControl(''),
title: new FormControl(''),
price: new FormControl(''),
hauter: new FormControl(''),
});
}
ngOnInit(): void {
this.getAll();
}
public getAll() {
this.bookSerive.getAll().subscribe((next) => {
this.books = next;
});
}
public delete(id: number) {
this.bookSerive.delete(id).subscribe((next) => {
this.getAll();
});
}
public showFormUpdate(book: Book) {
this.showForm = true;
this.formGroup = new FormGroup({
id:new FormControl(book.id),
title: new FormControl(book.title),
price: new FormControl(book.price),
hauter: new FormControl(book.hauter),
});
}
public update(){
console.log(this.formGroup.value);
this.bookSerive.update(this.formGroup.value).subscribe(next=>{
this.getAll();
this.showForm=false;
})
}
}
----------------------------------------------------------------------------------------------------
all-books.component.css (file khawi)
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
FOLDER src\app\services
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
book.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Book } from '../book';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class BookService {
constructor(private http:HttpClient) { }
url:string="http://localhost:8888/Books";
public getAll(){
return this.http.get<Book[]>(this.url);
}
public delete(id:number){
return this.http.delete(this.url+"/"+id);
}
public add(book:Book){
return this.http.post(this.url,book);
}
public update(book:Book){
this.http.put
return this.http.put(this.url+"/"+book.id ,book)
}
}
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
FICHIER SEPARER
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
npm install -g @angular/cli
npm -v
ng new Examen y y y
npm install -g json-server
set-executionpolicy unestricted
json-server db.json --port 8585
ng g i studente
id:string,
name: string,
ng g s service_studente
npm install -g bootstrap
ng g c allstudentes
db.json
"students": [
{
"id": "1",
"name": "leila"
}
]
}
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
ng serve-o (lancer le prog)
json-server --watch data/data.json --port 8888