我做了一个这样的守卫:
// 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
...我能够加载页面,没有任何错误。我做错了什么?
发布于 2016-07-29 05:00:27
在引导应用程序时,需要将服务MyService指定为提供者:
bootstrap(AppComponent, [
(...)
MyService, MyGuard
]);发布于 2016-07-29 05:01:44
您不需要声明服务,只需将其添加到构造函数中,然后使用下面的方法使用变量
constructor(private myService: MyService) {
}
func()
{
this.myService //like this
}并将其添加到bootstrap,如下所示
bootstrap(AppComponent, [
APP_ROUTER_PROVIDERS,
MyService
]).catch(err => console.error(err));https://stackoverflow.com/questions/38646594
复制相似问题