获取错误注入服务进入防范

时间:2016-07-28 20:56:13

标签: angular angular2-routing angular2-guards

我正在这样做一名警卫:

// MyGuard.ts
import { Injectable, Component } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot } from '@angular/router';

import { MyService } from './services/MyService';

@Component({
  providers: [MyService]
})

@Injectable()
export class MyGuard implements CanActivate {
  constructor(public s : MyService) {}

  canActivate(next: ActivatedRouteSnapshot, prev: RouterStateSnapshot) {
    this.s.doSomething();
    return true;
  }
}

服务在这里:

// MyService.ts
import { Injectable } from '@angular/core';
import * as _ from 'lodash';

@Injectable()
export class MyService {
  constructor() {
  }

  public doSomething() {
    return this;
  }
}

当我加载页面时,我收到此错误:

Error: Uncaught (in promise): No provider for MyService! (MyGuard -> MyService)

如果我在MyGuard的构造函数中删除了我声明服务的行

...
export class MyGuard implements CanActivate {
  constructor() {} // <--- here
  ...

我可以加载页面而不会出现任何错误。我做错了什么?

2 个答案:

答案 0 :(得分:1)

在引导应用程序时,您需要将服务MyService指定为提供程序:

bootstrap(AppComponent, [
  (...)
  MyService, MyGuard
]);

答案 1 :(得分:0)

您不需要声明服务只需将其添加到构造函数中,然后使用此

使用该变量
constructor(private myService: MyService) {
}

func()
{
this.myService //like this
}

并将其添加到像这样的引导程序

bootstrap(AppComponent, [ 
  APP_ROUTER_PROVIDERS,
  MyService
]).catch(err => console.error(err));