Redirect user without token

0

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

I'm saving a user and his token every time I log in to my platform, if someone without a token tries to access a route that needs token it can not and is redirected to the route "/", but it appears without nothing loaded, and I'm not sure how to resolve it.

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 that's how I get my user and my token,

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

Can anyone help me?

    
asked by anonymous 06.08.2018 / 14:47

1 answer

0

Use the navigate method 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;
}
    
06.08.2018 / 15:43