[英]Angular2 - No provider for LoggedInGuard
I'm making a Anuglar2 rc-4 web application. 我正在制作一个Anuglar2 rc-4网络应用程序。 I'm trying to restrict routes but when i add my login guard, it tells me there is no provider.
我正在尝试限制路由,但是当我添加我的登录守卫时,它告诉我没有提供商。 My normal login service code works fine, its just when i try to add the login guard and canActive routes.
我的正常登录服务代码工作正常,就在我尝试添加登录保护和canActive路由时。 Any ideas on how to fix this error?
有关如何解决此错误的任何想法?
routes.ts routes.ts
import { RouterConfig } from '@angular/router';
import { Home } from './components/home/home';
import { Login } from './components/login/login';
import { DashBoard } from './components/dashboard/dashboard';
import { User } from './components/user/user';
import { Store } from './components/store/store';
import { LoggedInGuard } from './models/logged-in.guard.ts';
export const routes: RouterConfig = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: Home, canActivate: [LoggedInGuard] },
{ path: 'login', component: Login },
{ path: 'dashboard', component: DashBoard },
{ path: 'user', component: User },
{ path: 'store', component: Store },
{ path: '**', redirectTo: 'home' }
];
boot.ts boot.ts
import { bootstrap } from '@angular/platform-browser-dynamic';
import { FormBuilder } from '@angular/common';
import { provideRouter } from '@angular/router';
import { HTTP_PROVIDERS, JSONP_PROVIDERS } from '@angular/http';
import { App } from './components/app/app';
import { routes } from './routes';
bootstrap(App, [
HTTP_PROVIDERS,
FormBuilder,
provideRouter(routes)
]);
logged-in.guard.ts 登录in.guard.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { LoginService } from '../services/login.service';
@Injectable()
export class LoggedInGuard implements CanActivate {
constructor(private ls: LoginService) {}
canActivate() {
return this.ls.isLoggedIn();
}
}
You have to inject your LoggedInGuard
service inside your application bootstrap function 您必须在应用程序引导功能中注入
LoggedInGuard
服务
bootstrap(App, [
HTTP_PROVIDERS,
FormBuilder,
provideRouter(routes),
LoggedInGuard // injected LoggedInGuard service provider here
]);
Note: This answer would not be the same for the current angular 2 updated version(rc.6), When you upgrade you need to create a
NgModule
where you are going to wrap up all the dependencies in single place, that timeLoggedInGuard
will go insideproviders
option of `NgModule注意:对于当前的角度2更新版本(rc.6),这个答案是不一样的。升级时你需要创建一个
NgModule
,你要在一个地方包装所有依赖项,那时LoggedInGuard
会去`NgModule的内部providers
选项
` `
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.