2016-01-31 179 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 –