Buenas tardes en el día de hoy me encuentro haciendo una autenticación de un usuario y aquí tengo un problema y es que al hacer clic en login o logout no me está cambiando la etiqueta o link a login o logout.Me toca hacer doble clic para qué cambie y otro click mas para que ejecute la accion y quiero que esto no pase, como puedo arreglar esto?.
En la parte del codigo se encuentra el componente y html del login, en el header lo mismo y el authenticacion services los metodos que se usan para hacer autenticaciones y verificaciones. Si alguien me podria ayudar en resolver esto estaria agredecido
este es mi componente header
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from 'src/app/services/authentication.service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
isLoggedIn = false;
constructor(
private authenthication: AuthenticationService,
private router: Router
) {}
ngOnInit(): void {}
verifyLooged() {
if (this.authenthication.verifyLooged()) {
this.router.navigateByUrl('home');
this.isLoggedIn = true;
}
}
onLogout() {
this.authenthication.logout();
this.isLoggedIn = false;
}
}
este es mi html del header
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" routerLink="/">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" routerLink="/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="/signup">Singup</a>
</li>
<li class="nav-item">
<a class="nav-link" *ngIf="!isLoggedIn" (click)="verifyLooged()" routerLink="/login">Login</a>
<a class="nav-link" *ngIf="isLoggedIn" (click)="onLogout()">LogOut</a>
</li>
</ul>
</div>
</div>
</nav>
authenticacion services
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, map, Observable } from 'rxjs';
import { ConfigurationService } from './configuration.service';
import { Router } from '@angular/router';
import { HeaderComponent } from '../shared/components/header/header.component';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
Accept: '*/*',
}),
};
@Injectable({
providedIn: 'root',
})
export class AuthenticationService {
private URL_BASE: string;
constructor(
private configuration: ConfigurationService,
private http: HttpClient,
private router: Router,
) {
this.URL_BASE = this.configuration.getUrlBase();
}
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
};
singup(data: any) {
return this.http.post(this.URL_BASE + 'signup', data);
}
login(email: string, password: string): Observable<> {
const user: any = {
email: email,
password: password,
};
return this.http
.post<>(
this.URL_BASE + 'login',
JSON.stringify(user),
this.httpOptions
)
.pipe(
map((res: any) => {
this.authSuccess(res.access_token);
return res;
})
);
}
authSuccess(token: string) {
localStorage.setItem('token', token);
}
getToken(): string | null {
return localStorage.getItem("token");
}
logout() {
localStorage.removeItem("token");
this.router.navigate(["login"]);
}
verifyLooged(): boolean{
const token = localStorage.getItem("token")
//return token ? true : false;
return !!token;
}
}
componente login
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from 'src/app/services/authentication.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
})
export class LoginComponent implements OnInit {
mensaje!: string;
form: any = {
email: null,
password: null,
};
//isLoggedIn = false;
isLoginFailed = false;
constructor(
private authenthication: AuthenticationService,
private router: Router
) {}
ngOnInit(): void {
// if (this.authenthication.verifyLooged()) {
// //this.isLoggedIn = true;
// this.router.navigateByUrl('home');
// }
}
submit(): void {
const { email, password } = this.form;
this.authenthication.login(email, password).subscribe({
next: (data) => {
//console.log(data);
this.mensaje = 'Datos Correctos';
this.router.navigateByUrl('home');
},
error: (err) => {
console.log(err.error.message);
this.isLoginFailed = true;
this.mensaje = 'Datos Incorrectos';
},
});
}
}
html del login
<form name="form" (ngSubmit)="f.form.valid && submit()" #f="ngForm" novalidate>
<div class="form-group">
<label for="inputEmail" class="form-label">Email address</label>
<input type="email" class="form-control" name="email" id="email" autocomplete="email" required
[(ngModel)]="form.email" #email="ngModel" aria-describedby="email">
</div>
<div class="form-group">
<label for="inputPassword" class="form-label">Password</label>
<input id="password" name="password" type="password" autocomplete="current-password" [(ngModel)]="form.password"
minlength="8" #password="ngModel" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div *ngIf="mensaje">{{mensaje}}</div>
esto pasa cuando me autentico
se puede observar que no cambia la etiqueta login, pero si le doy click de nuevo cambia, y si le vuelvo dar click me desloguea