angular 6 - Lost username when refresh F5 (but still logged)

841 views
Skip to first unread message

Belen Martin

unread,
Sep 28, 2018, 11:20:59 AM9/28/18
to Angular and AngularJS discussion
Hello, I had used (JWT) authentification with tokens for login in angular 6. The authentication works fine but I lost nameuser in toolbar when I refresh with f5. Anyone knows what it's happend?



here is the: auth.guard.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {

constructor(private router: Router) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('currentUser')) {
// logged in so return true
return true;
}

// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}

This is the service: authentication.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { User } from '../model/user';

@Injectable()
export class AuthenticationService {
constructor(private http: HttpClient) { }
currentUser$: Subject<User> = new Subject<User>();

login(username: string, password: string) {
return this.http.post<any>(`/users/authenticate`, { username: username, password: password })
.pipe(map(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
console.log(user.username + ' usuario logado');
}
this.currentUser$.next(user);
return user;
}));
}

logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
this.currentUser$.next(undefined);
}
}


Where I have the menu:

app.component.html

<div class="alternative">
<mat-toolbar color="accent">
<mat-toolbar-row>

<a routerLink="home" href="home" >
<span> <img src="assets/bmartinlogo.png"/>&nbsp; &nbsp; &nbsp; &nbsp;</span>
</a>
<mat-menu #menu="matMenu">
<button mat-menu-item [matMenuTriggerFor]="Contactos">Visitantes</button>
<button mat-menu-item [matMenuTriggerFor]="Visitas">Visitas</button>
</mat-menu>

<mat-menu #Contactos="matMenu">
<button mat-menu-item><a routerLink="contaclist" href="contaclist">Listado de visitantes</a></button>
</mat-menu>

<mat-menu #Visitas="matMenu">
<button mat-menu-item><a routerLink="visitlist" href="visitlist">Listado de visitas</a></button>
</mat-menu>
<button mat-button [matMenuTriggerFor]="menu"><mat-icon class="example-icon">menu </mat-icon>Menu</button>
<span class="example-fill-remaining-space"></span>
<p *ngIf="loggedInUser"> &nbsp;User:{{ loggedInUser.username }}</p>
</mat-toolbar-row>
</mat-toolbar>
<router-outlet></router-outlet>
</div>

app.component.ts

import { AuthenticationService } from './services/authentication.service';
import { Component, ViewChild, OnInit } from '@angular/core';
import { MatTableDataSource, MatSnackBar } from '@angular/material';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { ContactService } from './services/contact.service';


import { User } from './model/user';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'Visits Application';
loggedInUser: User;

constructor(public snackBar: MatSnackBar,
private _contactService: ContactService,
private dialog: MatDialog,
private _autenticationService: AuthenticationService,
) { }

ngOnInit() {
this._autenticationService.currentUser$.subscribe((user: User) => {
this.loggedInUser = user;
});
}
}


You can see the complete web : www.belenmartinsanchez.tk


THX¡¡¡¡¡¡

Belén Martín

Riccardo Sadocchi

unread,
Sep 28, 2018, 12:34:12 PM9/28/18
to Angular and AngularJS discussion
Hi Belén,
i think you can resolve whit a simple variable in your service.
Try some changes

// AuthenticationService:
// currenUser$: Subject<User> = new Subject<User>();
public currentUser:User;

// in the map on success
this.currentUser = user;

//in ngOnInit of AppComponent
if (this._autenticationService.currentUser){
 
this.loggedUser =
this._autenticationService.currentUser;
}else{
 
// go to login form
}

I work to an application with the same JWT token, we use this strategy and work fine.

Belen Martin

unread,
Sep 29, 2018, 2:55:31 AM9/29/18
to ang...@googlegroups.com
I did It but dont worked for me, sure i need to change anyone more thing :(

--
You received this message because you are subscribed to the Google Groups "Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Codewise IO

unread,
Sep 29, 2018, 7:17:29 AM9/29/18
to Angular and AngularJS discussion
I think you need to be using a BehaviorSubject with a default value being pulled from the local storage for your currentUser$ value.
Reply all
Reply to author
Forward
0 new messages