簡體   English   中英

在angular2中將服務注入服務

[英]Injecting services into services in angular2

我想編寫某種廣播機制來動態創建和使用我的用戶上下文中的EventEmitter 為此,我注入了一個EmitterService

@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組件中,我注入BroadcastService以確保每個子組件使用相同的廣播信道。 此外還注入了其他服務,如AuthService (在root也是如此,這基本上是我的用戶上下文)

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

AuthService (和其他人)正在使用BroadcastService來發送事件:

@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. 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. 乞求和哭泣,沒有幫助

最奇怪的部分是,這適用於我的其他服務之一,而不是與其他服務一起工作(好吧,我沒有嘗試所有,但我試過的那些不起作用)。 你有什么線索可能是什么問題嗎? 或者這可能只是一個錯誤(我在2.0.0-beta.2中使用angular2)

好像需要forwardRef

@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);
    }
}

也可能(或代替)有必要

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

取決於您的代碼組織方式。 當每個類在其自己的文件中定義時,這不是必需的。

另見Angular 2錯誤:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM