Angular 2 – Routing in service

I created a service to check for user token.

If the token hasn’t expired, do nothing. if it’s expired – redirect him to the login page.

My Service.ts relevant code:

checkToken(myError) {
        if (myError.json().error == "token_expired")
        {
            console.log("Your token has expired.");
            this.router.navigate( ['Login'] ); //Returns error
        } else {
            console.log("Do nothing");
        }
    }

The problem

EXCEPTION: TypeError: Cannot read property 'navigate' of undefined

My Service.ts

    import {Component,Injectable} from "angular2/core";
import {Router} from 'angular2/router';


@Injectable()

export class JwtService {
    private jwtToken = localStorage.getItem("jwt");

    constructor(public router: Router) 

    getToken() {
        return this.jwtToken;
    }

    checkToken(myError) {
        if (myError.json().error == "token_expired")
        {
            console.log("Your token has expired.");
            this.router.navigate( ['Login'] );
        } else {
            console.log("Do nothing");
        }
    }
}

My ROUTER_PROVIDERS is in my boot.ts file:

bootstrap(AppComponent, [
  JwtService,
  HTTP_PROVIDERS,
  ROUTER_PROVIDERS
]);

then why I can’t navigate from my service?

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest
constructor(public router: Router) 

should be

constructor(public router: Router) {}