Angular after login page not refreshed with newest info

Discussão em 'Angular' iniciado por Ilze, Outubro 27, 2024.

  1. Ilze

    Ilze Guest

    Im creating my first login in Angular. All works fine, user is logged in, and he is redirected to GiveDashboardComponent and on nav bar instead of "login" button - "logout" is displayed, and the same opposite when he logout. The problem is that those changes appear for me only if i manually refresh the page (thats how i know it works). Whats the right way how to do it in Angular, or did i choose some wrong approach in current code?

    My loginComponent:

    export class LoginComponent implements OnInit {
    user: User = new User();
    errorMessage: string = '';

    constructor(
    private authService: AuthenticationService,
    private router: Router,
    public sharedService: SharedService
    ) {}

    ngOnInit(): void {
    if (this.authService.currentUserValue?.id) {
    this.router.navigate(['/give-dashboard']);
    }
    }

    exit() {
    this.sharedService.showLoginComponent = false;
    }

    login() {
    this.authService.login(this.user).subscribe(
    (data) => {
    this.router.navigate(['/give-dashboard']);
    },
    (err) => {
    this.errorMessage = 'Username or password is incorrect.';
    console.log(err);
    }
    );
    }
    }



    Navigation bar component:

    export class NavBarComponent implements OnInit {
    isLoggedIn = false;
    user: User = new User();

    constructor(
    private router: Router,
    private authService: AuthenticationService,
    private sharedService: SharedService
    ) {}

    ngOnInit(): void {
    this.authService.loggedUser.subscribe((res) => {
    if (res) {
    this.isLoggedIn = true;
    } else {
    this.isLoggedIn = false;
    }
    });
    }
    showLogin() {
    this.sharedService.showLoginComponent = true;
    }

    logout() {
    this.authService.logout();
    this.router.navigate(['']);
    this.isLoggedIn = false;
    }
    }



    And the Dashboard component (i tried simply with navigating, but thats clearly not the way)

    export class GiveDashboardComponent implements OnInit {
    constructor(private router: Router) {}

    ngOnInit(): void {
    this.router.navigate(['/give-dashboard']);
    }
    }



    And authenticationService:

    export class AuthenticationService {
    public currentUser: Observable<User>;
    private currentUserSubject: BehaviorSubject<User>;
    private isLoggedIn = new BehaviorSubject<boolean>(this.userIsLoggedIn());
    public loggedUser = this.isLoggedIn.asObservable();

    constructor(private http: HttpClient) {
    let storageUser;
    const storageUserAsStr = localStorage.getItem('currentUser');
    if (storageUserAsStr) {
    storageUser = JSON.parse(storageUserAsStr);
    }
    this.currentUserSubject = new BehaviorSubject<User>(storageUser);
    this.currentUser = this.currentUserSubject.asObservable();
    }

    public get currentUserValue(): User {
    return this.currentUserSubject.value;
    }

    login(user: User): Observable<any> {
    return this.http.post<User>(API_URL + '/sign-in', user).pipe(
    map((res) => {
    if (res) {
    // set session-user
    this.setSessionUser(res);
    } else {
    return false;
    }
    return res;
    })
    );
    }

    register(user: User): Observable<any> {
    return this.http.post<User>(API_URL + '/sign-up', user).pipe(
    map((res) => {
    if (res) {
    this.setSessionUser(res);
    } else {
    return false;
    }
    return res;
    })
    );
    }

    setSessionUser(user: User) {
    localStorage.setItem('currentUser', JSON.stringify(user));
    this.currentUserSubject.next(user);
    }

    logout() {
    localStorage.removeItem('currentUser');
    this.currentUserSubject.next(new User());
    // this.currentUserSubject.next(null);
    }
    refreshToken(): Observable<any> {
    return this.http.post(
    API_URL + '/refresh-token?token=' + this.currentUserValue?.refreshToken,
    {}
    );
    }

    userIsLoggedIn() {
    return !!localStorage.getItem('currentUser');
    }
    }

    Continue reading...

Compartilhe esta Página