Angular2 - 没有LoggedInGuard的提供者

时间:2016-09-05 20:46:10

标签: javascript angular typescript angular-route-segment

我正在制作一个Anuglar2 rc-4网络应用程序。我试图限制路线但是当我添加我的登录守卫时,它告诉我没有提供者。我的正常登录服务代码工作正常,就在我尝试添加登录保护和canActive路由时。有关如何解决此错误的任何想法?

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

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)
]);

登录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();
  }
}

1 个答案:

答案 0 :(得分:4)

您必须在应用程序引导功能

中注入LoggedInGuard服务
bootstrap(App, [
    HTTP_PROVIDERS,
    FormBuilder,
    provideRouter(routes),
    LoggedInGuard // injected LoggedInGuard service provider here
]);
  

注意:这个答案对于当前的角度2更新版本(rc.6)不一样,升级时需要创建一个   NgModule您要将所有依赖项包装在其中   单个地点,那个时间LoggedInGuard将进入providers选项   'NgModule

`