2016-01-31 264 views
3

我想编写某种广播机制来在我的用户上下文中动态创建和使用EventEmitter。要做到这一点我注入了EmitterService在angular2中向服务注入服务

@Injectable() 
export class BroadcastService implements OnInit { 
    private _emitters: { [channel: string]: EventEmitter<any> } = {};  
    constructor() {}  
    get(channel: string): EventEmitter<any> { 
     if (!this._emitters[channel]) { 
      this._emitters[channel] = new EventEmitter(); 
     } 
     return this._emitters[channel]; 
    }  
    ngOnInit() { }  
} 

我的部件结构是这样的:

   [root] 
       | | 
      [comp-a][comp-b] 

在我root分量I注入BroadcastService以确保每个子组件使用相同的广播信道。另外像AuthService等业务都注入(在root过,这基本上我的用户上下文)使用的是BroadcastService对发出事件

@Component({ 
    provider: [BroadcastService, AuthService] 
}) 

AuthService(及其他):

@Injectable() 
export class AuthService extends BaseService {  
constructor(
     http: Http, 
     @Inject(BroadcastService) private emitterService: BroadcastService) 
    {    
     super(http);     
    } 
    ... 
    // Example usage of Broadcast 
    login(username: string, password: string) { 
     // do the login, when successfully: 
     this.emitterService.get("online").emit(true); 
    } 
} 

的错误我得到: EXCEPTION: Cannot resolve all parameters for 'AuthService'(Http, undefined @Inject(undefined)). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'AuthService' is decorated with Injectable.

我试了一下:

  1. 把另一根组件在顶部的当前根组件注入BroadcastService那里,同样的结果
  2. 添加/删除的@Inject的构造函数的参数,不改变
  3. 乞讨和哭泣,并没有帮助

最奇怪的部分是,这部作品与我的其他服务之一,不与他们的休息(当然,我没有尝试所有,但那些我试过没有工作)。你有什么线索可能是什么问题?或者这也许只是一个错误(我使用angular2在2.0.0-beta.2)

+0

你加'HTTP_PROVIDERS'到'引导(AppComponent,[...])'? '@Inject(BroadcastService)'是冗余的AFAIK。 –

+0

是的。我真的不知道,问题可能是什么 – letmejustfixthat

+0

我想这是源文件中的类的顺序。 'AuthService'和'BroadcastService'是否在同一个文件中?改变这两个类的顺序或使用'forwardRef' –

回答

5

好像需要还可能(或代替)

@Injectable() 
export class AuthService extends BaseService {  
constructor(
     http: Http, 
     @Inject(forwardRef(() => BroadcastService)) private emitterService: BroadcastService) 
    {    
     super(http);     
    } 
    ... 
    // Example usage of Broadcast 
    login(username: string, password: string) { 
     // do the login, when successfully: 
     this.emitterService.get("online").emit(true); 
    } 
} 

一个forwardRef是必要的,

@Component({ 
    provider: [BroadcastService, AuthService] 
}) 

取决于你的代码是如何组织的。 当每个类都在其自己的文件中定义时,这不是必需的。

又见Angular 2 error:

+0

太好了,谢谢。你有一个很好的指导去理解**究竟发生了什么**。我知道一般的前瞻性参考是什么以及为什么需要它。但是这种特殊情况对我来说仍然是一个迷宫 – letmejustfixthat

+1

类没有悬挂,因此尚不知道它们用作类型的地方。使用'forwardRef'时,类型的分辨率会延迟到整个文件内容已知时。另见http://blog.thoughtram.io/angular/2015/09/03/forward-references-in-angular-2.html和https://angular.io/docs/ts/latest/api/core/ forwardRef-function.html –