🐛 Add an id to modal service

pull/26/head
Alexis Feron 2 months ago
parent 7c0e5029f6
commit f3c229628c

@ -19,7 +19,7 @@ export class AuthGuard implements CanActivate {
return true; return true;
} else { } else {
this.router.navigate(['/']).then(() => { this.router.navigate(['/']).then(() => {
this.loginModalService.openModal(); this.loginModalService.openModal('login-modal');
}); });
return false; return false;
} }

@ -44,6 +44,7 @@ export class EditPinPopupComponent implements OnInit, AfterViewInit, OnDestroy {
inputFocused: boolean = false; inputFocused: boolean = false;
files: any[] = []; files: any[] = [];
isPinModalOpen: boolean = false; isPinModalOpen: boolean = false;
@Input() modalId!: string;
private modalOpenSubscription!: Subscription; private modalOpenSubscription!: Subscription;
private routerSubscription!: Subscription; private routerSubscription!: Subscription;
@ -79,7 +80,7 @@ export class EditPinPopupComponent implements OnInit, AfterViewInit, OnDestroy {
ngOnInit(): void { ngOnInit(): void {
// Initialiser le formulaire avec les valeurs de base // Initialiser le formulaire avec les valeurs de base
this.form.patchValue({ this.form.patchValue({
title: this.pin?.title || 'vide', title: this.pin?.title || '',
description: this.pin?.description || '', description: this.pin?.description || '',
location: "Chargement de l'adresse...", location: "Chargement de l'adresse...",
}); });
@ -100,7 +101,6 @@ export class EditPinPopupComponent implements OnInit, AfterViewInit, OnDestroy {
.pipe(take(1)) .pipe(take(1))
.subscribe( .subscribe(
(address) => { (address) => {
console.log('Adresse récupérée:', address);
if (address && address.display_name) { if (address && address.display_name) {
this.form.patchValue({ location: address.display_name }); this.form.patchValue({ location: address.display_name });
} else { } else {
@ -119,16 +119,14 @@ export class EditPinPopupComponent implements OnInit, AfterViewInit, OnDestroy {
} }
// S'abonner aux changements d'état du modal // S'abonner aux changements d'état du modal
this.modalOpenSubscription = this.modalService.showModal$.subscribe( this.modalOpenSubscription = this.modalService
(state) => { .getModalState(this.modalId)
.subscribe((state) => {
this.isPinModalOpen = state; this.isPinModalOpen = state;
// Lorsque le modal s'ouvre, s'assurer qu'il est dans le body
if (state) { if (state) {
setTimeout(() => this.moveModalToBody(), 0); setTimeout(() => this.moveModalToBody(), 0);
} }
} });
);
// S'abonner aux événements de navigation du router // S'abonner aux événements de navigation du router
this.routerSubscription = this.router.events this.routerSubscription = this.router.events
@ -217,7 +215,6 @@ export class EditPinPopupComponent implements OnInit, AfterViewInit, OnDestroy {
.toPromise(); .toPromise();
if (address) { if (address) {
console.log("Données d'adresse :", JSON.stringify(address));
this.form.get('location')?.setValue(address.display_name); this.form.get('location')?.setValue(address.display_name);
break; break;
} }
@ -259,10 +256,10 @@ export class EditPinPopupComponent implements OnInit, AfterViewInit, OnDestroy {
} }
openPinModal() { openPinModal() {
this.modalService.openModal(); this.modalService.openModal(this.modalId);
} }
closePinModal() { closePinModal() {
this.modalService.closeModal(); this.modalService.closeModal(this.modalId);
} }
} }

@ -14,6 +14,6 @@ export class HomeNavbarComponent {
constructor(private modalService: ModalService) {} constructor(private modalService: ModalService) {}
openLoginModal() { openLoginModal() {
this.modalService.openModal(); this.modalService.openModal('login-modal');
} }
} }

@ -11,6 +11,6 @@ export class HomePageComponent {
constructor(private loginModalService: ModalService) {} constructor(private loginModalService: ModalService) {}
openLogin() { openLogin() {
this.loginModalService.openModal(); this.loginModalService.openModal('login-modal');
} }
} }

@ -21,6 +21,7 @@ import { ModalService } from '../../services/modal/modal.service';
styleUrl: './login-page.component.css', styleUrl: './login-page.component.css',
}) })
export class LoginPageComponent { export class LoginPageComponent {
modalId: string = 'login-modal';
userForm: FormGroup; userForm: FormGroup;
user: User = { login: '', password: '' }; user: User = { login: '', password: '' };
errorMessage: string = ''; errorMessage: string = '';
@ -31,7 +32,7 @@ export class LoginPageComponent {
private loginService: LoginService, private loginService: LoginService,
private fb: FormBuilder, private fb: FormBuilder,
private router: Router, private router: Router,
private loginModalService: ModalService, private modalService: ModalService,
private localStorageService: LocalStorageService private localStorageService: LocalStorageService
) { ) {
this.userForm = this.fb.group({ this.userForm = this.fb.group({
@ -44,9 +45,11 @@ export class LoginPageComponent {
} }
ngOnInit() { ngOnInit() {
this.modalSub = this.loginModalService.showModal$.subscribe((open) => { this.modalSub = this.modalService
this.isLoginModalOpen = open; .getModalState(this.modalId)
}); .subscribe((open) => {
this.isLoginModalOpen = open;
});
} }
ngOnDestroy() { ngOnDestroy() {
@ -65,26 +68,26 @@ export class LoginPageComponent {
this.loginService.login(this.user.login, this.user.password).subscribe({ this.loginService.login(this.user.login, this.user.password).subscribe({
next: (response) => { next: (response) => {
console.log('Connexion OK: ', response);
this.localStorageService.setToken(response.access_token); this.localStorageService.setToken(response.access_token);
this.closeLoginModal(); this.closeLoginModal();
setTimeout(() => { setTimeout(() => {
this.router.navigate(['/map']); this.router.navigate(['/map']);
this.modalService.closeModal(this.modalId);
}, 1); }, 1);
}, },
error: (response) => { error: (response) => {
console.log('Connexion KO: ', response.error.detail); console.error('Connexion KO: ', response.error.detail);
this.errorMessage = response.error.detail; this.errorMessage = response.error.detail;
}, },
}); });
} }
openLoginModal() { openLoginModal() {
this.isLoginModalOpen = true; this.modalService.openModal(this.modalId);
} }
closeLoginModal() { closeLoginModal() {
this.isLoginModalOpen = false; this.modalService.closeModal(this.modalId);
} }
} }

@ -89,10 +89,6 @@ export class NavbarComponent implements OnInit {
debounceTime(300), // Attendre 300ms après la dernière frappe debounceTime(300), // Attendre 300ms après la dernière frappe
distinctUntilChanged(), // Ignorer si la nouvelle valeur est la même que la précédente distinctUntilChanged(), // Ignorer si la nouvelle valeur est la même que la précédente
switchMap((searchTerm) => { switchMap((searchTerm) => {
console.log(
'Value change : ',
this.searchForm.get('searchControl')?.valueChanges
);
const trimmedQuery = searchTerm?.trim(); const trimmedQuery = searchTerm?.trim();
if (trimmedQuery && trimmedQuery.length > 1) { if (trimmedQuery && trimmedQuery.length > 1) {
return of(this.filterPins(trimmedQuery)); return of(this.filterPins(trimmedQuery));
@ -109,15 +105,12 @@ export class NavbarComponent implements OnInit {
) )
.subscribe((filteredPins) => { .subscribe((filteredPins) => {
this.pinsFiltered = filteredPins; this.pinsFiltered = filteredPins;
console.log('Pins filtrés : ', this.pinsFiltered);
}); });
} }
filterPins(searchTerm: string): Pin[] { filterPins(searchTerm: string): Pin[] {
const filteredPins: Pin[] = []; const filteredPins: Pin[] = [];
console.log('Pins : ', this.pins);
if (this.pins.length === 0) { if (this.pins.length === 0) {
this.pins = this.pinService.getPins(); this.pins = this.pinService.getPins();
} }
@ -127,7 +120,6 @@ export class NavbarComponent implements OnInit {
pin.title && pin.title &&
pin.title.toLowerCase().includes(searchTerm.toLowerCase()) pin.title.toLowerCase().includes(searchTerm.toLowerCase())
) { ) {
console.log('Search term : ', searchTerm, ' / Pin trouvé : ', pin);
filteredPins.push(pin); filteredPins.push(pin);
} }
}); });
@ -144,7 +136,6 @@ export class NavbarComponent implements OnInit {
queryParams: queryParams, queryParams: queryParams,
queryParamsHandling: 'merge', // Conserve les autres paramètres de requête queryParamsHandling: 'merge', // Conserve les autres paramètres de requête
}); });
console.log('Redirection avec ID :', pin.id);
} }
onFocus(): void { onFocus(): void {

@ -1,5 +1,5 @@
<div class="flex mb-2 justify-end items-center"> <div class="flex mb-2 justify-end items-center">
<app-edit-pin-popup [pin]="pin"></app-edit-pin-popup> <app-edit-pin-popup [pin]="pin" [modalId]="pin.id"></app-edit-pin-popup>
<button <button
class="p-1 text-red-500 rounded hover:bg-red-100 focus:outline-none ml-2 flex items-center" class="p-1 text-red-500 rounded hover:bg-red-100 focus:outline-none ml-2 flex items-center"
aria-label="Delete" aria-label="Delete"

@ -66,7 +66,6 @@ export class RegisterPageComponent {
.register(this.user.login, this.user.password) .register(this.user.login, this.user.password)
.subscribe({ .subscribe({
next: (response) => { next: (response) => {
console.log('Register OK: ', response);
this.localStorageService.setToken(response.access_token); this.localStorageService.setToken(response.access_token);
this.closeRegisterModal(); this.closeRegisterModal();
setTimeout(() => { setTimeout(() => {
@ -74,7 +73,7 @@ export class RegisterPageComponent {
}, 1); }, 1);
}, },
error: (response) => { error: (response) => {
console.log('Register KO: ', response.error.detail); console.error('Register KO: ', response.error.detail);
this.errorMessage = response.error.detail; this.errorMessage = response.error.detail;
}, },
}); });

@ -8,10 +8,7 @@ import { ModalService } from '../modal/modal.service';
export class LocalStorageService { export class LocalStorageService {
private readonly AUTH_TOKEN_KEY = 'auth_token'; private readonly AUTH_TOKEN_KEY = 'auth_token';
constructor( constructor(private router: Router, private modalService: ModalService) {}
private router: Router,
private loginModalService: ModalService
) {}
setToken(token: string): void { setToken(token: string): void {
localStorage.setItem(this.AUTH_TOKEN_KEY, token); localStorage.setItem(this.AUTH_TOKEN_KEY, token);
@ -26,7 +23,7 @@ export class LocalStorageService {
if (expirationDate < new Date()) { if (expirationDate < new Date()) {
this.removeToken(); // Remove expired token this.removeToken(); // Remove expired token
this.router.navigate(['/']).then(() => { this.router.navigate(['/']).then(() => {
this.loginModalService.openModal(); // Open login modal this.modalService.openModal('login-modal');
}); });
return null; return null;
} }

@ -3,15 +3,20 @@ import { BehaviorSubject } from 'rxjs';
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class ModalService { export class ModalService {
private showModalSubject = new BehaviorSubject<boolean>(false); private modals: Map<string, BehaviorSubject<boolean>> = new Map();
showModal$ = this.showModalSubject.asObservable(); getModalState(id: string): BehaviorSubject<boolean> {
if (!this.modals.has(id)) {
this.modals.set(id, new BehaviorSubject<boolean>(false));
}
return this.modals.get(id)!;
}
openModal() { openModal(id: string) {
this.showModalSubject.next(true); this.getModalState(id).next(true);
} }
closeModal() { closeModal(id: string) {
this.showModalSubject.next(false); this.getModalState(id).next(false);
} }
} }

Loading…
Cancel
Save