Skip to content

Commit

Permalink
Records ok
Browse files Browse the repository at this point in the history
  • Loading branch information
anthonycros committed Jan 19, 2022
1 parent fcf1d45 commit b11994e
Show file tree
Hide file tree
Showing 10 changed files with 111 additions and 104 deletions.
5 changes: 3 additions & 2 deletions src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ import { RecordDetailsComponent } from './record-details/record-details.componen

const routes: Routes = [
//Route par défaut
{ path: '', redirectTo: '/channels', pathMatch: 'full' },
{ path: '', redirectTo: '/', pathMatch: 'full' },
{ path: 'channels', component: ChannelListComponent },
{ path: 'records', component: RecordListComponent },
{ path: 'channel/:id', component: ChannelDetailsComponent },
{ path: 'channel/new', component: ChannelDetailsComponent },
{ path: 'records', component: RecordListComponent },
{ path: 'record/:id', component: RecordDetailsComponent },
{ path: 'record/:new', component: RecordDetailsComponent },
];

@NgModule({
Expand Down
22 changes: 10 additions & 12 deletions src/app/channel-details/channel-details.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { ChannelService } from '../channel.service';
export class ChannelDetailsComponent implements OnInit {

@Input() channel?: Channel;
// channel: Channel | undefined;

submitted: boolean = false;
// contexte : new ou update
Expand All @@ -29,28 +28,25 @@ export class ChannelDetailsComponent implements OnInit {
// D'abord on récupère l'id de la chaine depuis la route courante
const routeParams = this.route.snapshot.paramMap;
const channelIdFromRoute = routeParams.get('id');

console.log(`Le channelIdFromRoute vaut : ${channelIdFromRoute}`)

// Puis on cherche la chaine correspondant à cet id
if (channelIdFromRoute == "new") {
console.log(`On est dans une création de channel`)
// On est dans le contexte de création d'une chaîne
this.context_mode = "new";
//test pour générer nouvel ID
let localChannels: Channel[];
let localNb;
console.log('On entre dans le calcul du genid');
this.channelService.getChannels().then(autreresultat=> {
localChannels = autreresultat;
console.log(`localChannels[0].name vaut : ${localChannels[0].name}`);
console.log(`localChannels.lenght vaut : ${localChannels.length}`);
//console.log('On entre dans le calcul du genid pour new channel');
this.channelService.getChannels().then(resultat=> {
localChannels = resultat;
localNb = this.channelService.genChannelId(localChannels);
console.log(`L'id récupéré vaut : ${localNb}`)

//console.log(`L'id récupéré vaut : ${localNb}`)
this.channel = {id: localNb, name: "", url: ""};
})}
})
}
else
{
// On est dans le contexte d'affichage / modification d'une chaîne existante
this.channelService.getChannels().then(resultat=>
{
this.context_mode = "update";
Expand All @@ -68,9 +64,11 @@ export class ChannelDetailsComponent implements OnInit {
this.submitted = true;
if (this.channel) {
if (this.context_mode == "update") {
// On est dans le contexte d'affichage / modification d'une chaîne existante
this.channelService.updateChannel(this.channel).subscribe(() => this.goBack());
}
else if (this.context_mode == "new") {
// On est dans le contexte de création d'une chaîne
this.channelService.createChannel(this.channel).subscribe(() => this.goBack());
}
}
Expand Down
18 changes: 1 addition & 17 deletions src/app/channel-list/channel-list.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,4 @@ <h2>Liste des Chaînes</h2>
<button (click)="test_anthoApi()">
Test genChannelIdApi
</button>
</div>

<!-- <div class="channel-item" *ngFor="let channel of channels | async">
<h3>
<a [title]="'Détails de '+channel.name">
{{ channel.name }}
</a>
</h3>
<p>
URL : {{ channel.url }}
</p>
<button (click)="test_button()">
Test
</button>
</div> -->
</div>
17 changes: 1 addition & 16 deletions src/app/channel-list/channel-list.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,34 +9,19 @@ import { ChannelService } from '../channel.service';
})
export class ChannelListComponent implements OnInit {

//channel: Channel;
channels = this.channelService.getChannels();
channelstemp: Channel[];
channelstempApi: Channel[];

constructor(private channelService: ChannelService) { }

ngOnInit(): void {

ngOnInit(): void {
}

delete(channel: Channel) {
//console.log(`Appel de la fonction delete sur la chaîne dont l'id est : ${channel.id}`);
if (channel) {
this.channelService.deleteChannel(channel.id).subscribe()
}
}

newchannel () {
console.log('Appel de new channel dans channel list');
this.channelService.getChannels().then(resultat=> {
this.channelstemp = resultat
})
let nb = this.channelService.genChannelId(this.channelstemp)
console.log(`antho en direct dit : ${nb}`)
window.alert(`antho en direct dit : ${nb}`)
};

test_anthoApi () {
console.log('On entre dans test_anthoapi');
};
Expand Down
10 changes: 5 additions & 5 deletions src/app/channel.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ export class ChannelService {
return this.http.delete(`${this.channelUrl}/delete/${idChannel}`, this.httpOptions)
}

// genId method to ensure that a channel always has an id.
// If the channel array is empty,
// the method below returns the initial number (1).
// if the channel array is not empty, the method below returns the highest
// channel id + 1.
// méthode genId pour générer un id unique et incrémental lors de la création d'une chaîne
// Si le tableau est vide,
// la méthode génère (1).
// Si le tableau n'est pas vide, la méthode génère l'idmax trouvé + 1

genChannelId(channels: Channel[]): number {
return channels.length > 0 ? Math.max(...channels.map(channel => channel.id)) + 1 : 1;
}
Expand Down
12 changes: 2 additions & 10 deletions src/app/record-details/record-details.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,8 @@
<h3>Détails de l'enregistrement {{ record.name }}</h3>
<form (ngSubmit)="onSubmit()" #recordForm="ngForm">

<div class="form-group">
<label for="id">Id de l'enregistrement : </label>
<input type="text" class="form-control "id="id"
required
[(ngModel)]="record.id" name="id"
#id="ngModel">
<div [hidden]="id.valid || id.pristine"
class="alert alert-danger">>
L'id est obligatoire
</div>
<div class="form-group">
<label for="id">Id de l'enregistrement : {{ record.id }} </label>
</div>

<div class="form-group">
Expand Down
65 changes: 52 additions & 13 deletions src/app/record-details/record-details.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ import { ChannelService } from '../channel.service';
})
export class RecordDetailsComponent implements OnInit {

record: Record ;
channel: Channel ;
@Input() record?: Record ;
channels: Array<Channel> ;


submitted = false;
submitted: boolean = false;
targetChannelid: number;
// contexte : new ou update
context_mode: string = "";

constructor(
private route: ActivatedRoute,
Expand All @@ -35,29 +35,68 @@ export class RecordDetailsComponent implements OnInit {
const routeParams = this.route.snapshot.paramMap;
const recordIdFromRoute = routeParams.get('id');

// Puis on cherche la chaine correspondant à cet id
this.recordService.getRecords().then(resultat=>
// On charge les chaînes pour alimenter la combo des chaines
this.channelService.getChannels().then(resultat=>
{
this.record = resultat.find(record => record.id === Number(recordIdFromRoute))
this.targetChannelid = this.record.idch
this.channels = resultat
})

this.channelService.getChannels().then(resultat=>

// Puis on cherche la chaine correspondant à cet id
if (recordIdFromRoute == "new") {
// On est dans le contexte de création d'un enregistrement
this.context_mode = "new";
//test pour générer nouvel ID
let localRecords: Record[];
let localNb;
//console.log('On entre dans le calcul du genid pour new record');
this.recordService.getRecords().then(resultat => {
localRecords = resultat;
localNb = this.recordService.genRecordId(localRecords);
//console.log(`L'id récupéré vaut : ${localNb}`);
this.record = {id: localNb, name: "", idch: null, namech: "", urlch: "", recbegin: "", recend: "", done: false, archived: false};
})
}
else
{
// On est dans le contexte d'affichage / modification d'un enregistrement existant
this.recordService.getRecords().then(resultat=>
{
this.channels = resultat
this.context_mode = "update";
this.record = resultat.find(record => record.id === Number(recordIdFromRoute))
this.targetChannelid = this.record.idch
this.onChangeChannel();
})

}
}

goBack(): void {
this.location.back();
}

onSubmit() { this.submitted = true; }
//Todo : corriger le goback apres update
onSubmit() {
this.submitted = true;
if (this.record) {
if (this.context_mode == "update") {
// On est dans le contexte d'affichage / modification d'un enregistrement existant
console.log(`mode update enreg`);
this.recordService.updateRecord(this.record).subscribe(() => this.goBack());
}
else if (this.context_mode == "new") {
// On est dans le contexte de création d'un enregistrement
console.log(`mode new enreg`);
this.recordService.createRecord(this.record).subscribe(() => this.goBack);
}
else {
console.log(`mode autre enreg`);
}
}
}

onChangeChannel() {
const chosenChannel = this.channels.find((element: Channel)=>{return element.id==this.targetChannelid});
this.record.idch = chosenChannel.id
this.record.namech = chosenChannel.name
this.record.urlch = chosenChannel.url
}
}
18 changes: 3 additions & 15 deletions src/app/record-list/record-list.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,6 @@ <h2>Liste des Enregistrements</h2>
</li>
</ul>

<!-- <div class="record-item" *ngFor="let record of records | async">
<h3>
<a [title]="'Détails de '+record.name">
{{ record.name }}
</a>
</h3>
<h2>
Chaîne : {{ record.namech }}
</h2>
<p>
Début : {{ record.recbegin }}
Fin : {{ record.recend }}
</p>
</div> -->
<nav>
<a routerLink="/record/new">Ajouter</a>
</nav>
5 changes: 3 additions & 2 deletions src/app/record-list/record-list.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ export class RecordListComponent implements OnInit {
}

delete(record: Record) {
window.alert(`Appeler la fonction delete sur l'enregistrement dont l'id est : ${record.id}`);
if (record) {
this.recordService.deleteRecord(record.id).subscribe()
}
}

}
43 changes: 31 additions & 12 deletions src/app/record.service.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,49 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { Record } from './record';
//import { writeFileSync, readFileSync } from 'fs';
//import fs from 'fs';

@Injectable({
providedIn: 'root'
})
export class RecordService {

private recordUrl = 'https://recordantho.mysites.fr:3443/record'; // URL to web api

constructor(private http: HttpClient) { }
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

// Récupération de la liste des enregistrements
getRecords():Promise <Array<Record>> {
return new Promise((resolve, reject)=>
{
this.http.get<Array<Record>>('/assets/records.json').subscribe(resultat=>{ resolve(resultat) });
this.http.get<Array<Record>>(`${this.recordUrl}/list`).subscribe(resultat=>{ resolve(resultat) });
});
}

updateJson(record: Record) {
this.getRecords().then(allRecords=>{
allRecords[allRecords.findIndex(element=>{
return element.id == record.id
})] = record
})
//fs.writeFile('/assets/records.json', allRecords)

// Création d'un enregistrement
createRecord(record: Record): Observable<any> {
return this.http.post(`${this.recordUrl}/addrecord`, record, this.httpOptions)
}

// Update d'un enregistrement
updateRecord(record: Record): Observable<any> {
return this.http.put(`${this.recordUrl}/update`, record, this.httpOptions)
}

// Suppression d'une chaîne
deleteRecord(idRecord: Number): Observable<any> {
return this.http.delete(`${this.recordUrl}/delete/${idRecord}`, this.httpOptions)
}

// méthode genId pour générer un id unique et incrémental lors de la création d'un enregistrement
// Si le tableau est vide,
// la méthode génère (1).
// Si le tableau n'est pas vide, la méthode génère l'idmax trouvé + 1

genRecordId(records: Record[]): number {
return records.length > 0 ? Math.max(...records.map(record => record.id)) + 1 : 1;
}
}

0 comments on commit b11994e

Please sign in to comment.