我创建了一个服务来检查用户令牌。Angular 2 - 在服务路由
如果令牌未过期,则什么也不做。如果它已过期 - 将他重定向到登录页面。
我Service.ts相关代码:
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");
}
}
问题
EXCEPTION: TypeError: Cannot read property 'navigate' of undefined
我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");
}
}
}
我ROUTER_PROVIDERS
是我boot.ts
file:
bootstrap(AppComponent, [
JwtService,
HTTP_PROVIDERS,
ROUTER_PROVIDERS
]);
那么为什么我无法从我的服务中导航?
看起来你有'@Injectable()'这是多余的组件。 –
您将'Router'注入到'AppComponent',但在您的服务中使用它。你是否也向服务注入了'Router'? –
我已经在我的AppComponent中使用了它,但现在我需要在我的服务中使用它。我帖子中的代码来自我的服务。 – TheUnreal