Angular 6+: Page update goes to the application’s login area

Asked

Viewed 120 times

1

I performed the composition of my Canactivate and Canload, through the Loggedinguard class. The problem is that whenever I refresh the page, I am redirected to the Login page, even logged in. Below my class Loggedinguard

@Injectable()
export class LoggedInGuard implements CanLoad, CanActivate {
  constructor(private signinService: SigninService, private router: Router) { }

  checkAuthentication(path: string): boolean {
    const loggedin = this.signinService.isLoggedin();
    if (!loggedin) {
      this.router.navigate([ this.signinService.handleLogin(`/${ path }`) ]);
    }
    return loggedin;
  }

  canLoad(route: Route): boolean {
    return this.checkAuthentication(route.path);
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.checkAuthentication(route.routeConfig.path);
  }

}

My Signservice:

@Injectable({
  providedIn: 'root'
})
export class SigninService {

  private baseUrl: string;
  private user: User;
  private lastUrl: string;

  constructor(private http: HttpClient, private router: Router) {
    this.baseUrl = `${environment.url}/auth/signin`;
    this.router.events
      .filter(e => e instanceof NavigationEnd)
      .subscribe((e: NavigationEnd) => this.lastUrl = e.url);
  }

  public isLoggedin(): boolean {
    return this.user !== undefined && localStorage.getItem('token') !== undefined;
  }

  public login(username: string, password: string): Observable<User> {
    const params = new HttpParams()
      .set('username', username)
      .set('password', password);
    return this.http.post<User>(`${this.baseUrl}`, params).do((user: User) => this.user = user);
  }

  public logout(): void {
    localStorage.clear();
    this.user = undefined;
    this.handleLogin('/');
  }

  public handleLogin(path: string = this.lastUrl) {
    this.router.navigate(['/signin', btoa(path)]);
  }

  public get UserDetail(): User {
    return this.user;
  }


}

Services are set within responsibility providers. In my, Signincomponent and perform the Login as follows:

public login(): void {
    console.log(this.signinForm);
    this.signinService.login(this.signinForm.value.username, this.signinForm.value.password ).subscribe((user: User) => {
      this.user = user;
      localStorage.setItem('token', this.user.token.token);
      this.isSuccess = true;
      this.message = 'Usuário encontrado. Aguarde um momento!';
    }, (err: HttpErrorResponse) => {
        this.isSuccess = false;
        this.message = err.error.error.message;
      console.error(err);
      }, () => {
        this.router.navigate([ atob(this.navigateTo) ]);
    });
  }
  • the method isLoggedin ta returning true or false??

  • It’s @Eduardovargas! So... It seems like he loses the user reference when he updates the page. Something I wouldn’t want to happen. so, the method to be fake! I did localstorage only, but I don’t find it very confident.

1 answer

0


Solution 1: Since User is not an Interface, the reference is lost. So, I changed the format of Interface to Class, and I instated the same.

this.user = new User();

The way above, I couldn’t lose my reference.

The other way is to work with localstorage:

localStorage.setItem('token', this.user.token.token);

It’s from Prache, when using the set with a unique tooken, then set token, which is such a common word within applications can generate conflicts if you have other applications that use the same term. It’s rare, but I’ve seen cases happen. So, I file as thiago_token, for example.

Always when updating, the system will check if the token is in localstorage or sessionstorage. Where you prefer to save!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.