I have this problem when I log in to the username section, I get undefined undefined instead of the username that comes from my database, but the moment I refresh the full page, I get the username correctly. I don't know why. I attach my code since I can't see where I'm wrong:
auth.services.ts
import { IMeData, ISession } from '@core/services/interfaces/session.interface';
import { LOGIN_QUERY, ME_DATA_QUERY } from '@graphql/operations/query/user';
import { Injectable } from '@angular/core';
import { ApiService } from '@graphql/services/api.service';
import { Apollo } from 'apollo-angular';
import { map } from 'rxjs/operators';
import { HttpHeaders } from '@angular/common/http';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class AuthService extends ApiService {
accessVar = new Subject<IMeData>();
accessVar$ = this.accessVar.asObservable();
constructor(apollo: Apollo) {
super(apollo);
}
updateSession(newValue: IMeData) {
this.accessVar.next(newValue);
}
start() {
if (this.getSession() !== null) {
this.getMe().subscribe((result: IMeData) => {
if (!result.status) {
this.resetSession();
return;
}
this.updateSession(result);
});
console.log('Sesión iniciada');
return;
}
this.updateSession({
status: false,
});
console.log('Sesión no iniciada');
}
/** Añadir los metodos para consumir la info de la API */
login(email: string, password: string) {
return this.get(LOGIN_QUERY, { email, password, include: false }).pipe(
map((result: any) => {
return result.login;
})
);
}
getMe() {
return this.get(ME_DATA_QUERY, {
include: false,
},
{
headers: new HttpHeaders({
Authorization: (this.getSession() as ISession).token
})
}).pipe(map((result: any) => {
return result.me;
})
);
}
setSession(token: string, expiresTimeInHours = 24) {
const date = new Date();
date.setHours(date.getHours() + expiresTimeInHours);
const session: ISession = {
expiresIn: new Date(date).toISOString(),
token
};
localStorage.setItem('session', JSON.stringify(session));
}
getSession(): ISession {
return JSON.parse(localStorage.getItem('session'));
}
resetSession() {
localStorage.removeItem('session');
this.updateSession({status: false});
}
}
login.component.ts
import { Component } from '@angular/core';
import { AuthService } from '@core/services/auth.service';
import { ILoginForm, IResultLogin, } from '@core/services/interfaces/login.interface';
import { basicAlert } from '@shared/alerts/toasts';
import { TYPE_ALERT } from '@shared/alerts/values.config';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss'],
})
export class LoginComponent {
login: ILoginForm = {
email: '',
password: '',
};
constructor(private auth: AuthService, private router: Router) {}
init() {
console.log(this.login);
this.auth.login(this.login.email, this.login.password).subscribe(
(result: IResultLogin) => {
console.log(result);
if (result.status) {
if (result.token !== null) {
basicAlert(TYPE_ALERT.SUCCESS, result.message);
this.auth.setSession(result.token);
this.auth.updateSession(result);
this.router.navigate(['/home']);
return;
}
basicAlert(TYPE_ALERT.WARNING, result.message);
return;
}
basicAlert(TYPE_ALERT.INFO, result.message);
});
}
}
navbar.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from '@core/services/auth.service';
import { IMeData } from '@core/services/interfaces/session.interface';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.scss'],
})
export class NavbarComponent implements OnInit {
session: IMeData = {
status: false,
};
access = false;
role: string;
userLabel = '';
constructor(private authService: AuthService) {
this.authService.accessVar$.subscribe((result) => {
console.log(result.status);
this.session = result;
this.access = this.session.status;
this.role = this.session.user?.role;
this.userLabel = `${ this.session.user?.name } ${ this.session.user?.lastname }`;
});
}
ngOnInit(): void {}
logout() {
this.authService.resetSession();
}
}
public.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from '@core/services/auth.service';
@Component({
selector: 'app-public',
templateUrl: './public.component.html',
styleUrls: ['./public.component.scss'],
})
export class PublicComponent implements OnInit {
constructor(private auth: AuthService) {}
ngOnInit(): void {
this.auth.start();
}
}