我正在制作这样的警卫:
// 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
...
我能够加载页面而没有任何错误。我究竟做错了什么?