Redirect user without token

Asked

Viewed 40 times

0

Talk guys, good morning, so I have a problem and I’m not sure how to solve, (maybe it’s in the way I implemented it), well:

i am saving a user and his token every time I log in to my platform, in case someone without token tries to access a route that needs token he cannot and is redirected to the route " / ", however it appears without anything loaded, and I’m not sure how to fix this.

import { Component, OnInit } from "@angular/core";
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../environments/environment';

@Component({
    selector: 'app-admin',
    templateUrl: './admin.component.html',
    styleUrls: ['./admin.component.scss']
})
export class AdminComponent implements OnInit {
    user = JSON.parse(localStorage.getItem('user'));
    token = this.user.token;

    constructor(private http: HttpClient) { }

    ngOnInit() {
        

    }

    downloadStudents() {
        let url = environment.apiUrl + 'admin/csv';
        this.http.get(url, { responseType: "text" })
            .subscribe(res => {
                let csv = 'data:text/csv;charset=utf-8,' + res;
                let data = encodeURI(csv);

                let link = document.createElement('a');
                link.setAttribute('href', data);
                link.setAttribute('download', 'alunos.csv');
                link.click();
            })
    }
}

This is my code. And as you can see this is how I get my user and my token,

user = JSON.parse(localStorage.getItem('user')); token = this.user.token;

Can anyone help me ?

1 answer

0


Uses the method navigate of router angular to redirect.

 constructor(private router: Router, private http: HttpClient) { }
 user; 
 token;
 ngOnInit(){
   this.user = JSON.parse(localStorage.getItem('user'));

   if (!this.user || !this.user.token) 
    this.router.navigate(['/']);
   else
    this.token = this.user.token;
}
  • 1

    Thanks for the help expensive, I managed to do this way solved the problem of redirecting, but I realized that with this validation on the front I am not totally safe, I see now to do in the back this validation

Browser other questions tagged

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