【问题标题】:Injecting services into services in angular2在angular2中将服务注入服务
【发布时间】:2016-05-09 02:34:16
【问题描述】:

我想编写某种广播机制来在我的用户上下文中动态创建和使用EventEmitters。为此,我注入了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.

我尝试了什么:

  1. 将另一个根组件放在当前根组件的顶部以将BroadcastService 注入那里,结果相同
  2. 在构造函数参数中添加/删除@Inject,无更改
  3. 乞求哭泣,无济于事

最奇怪的是,这适用于我的其他服务之一,但不适用于其他服务(好吧,我没有尝试所有,但我尝试过的那些都不起作用)。你有什么线索可能是什么问题吗?或者这可能只是一个错误(我在 2.0.0-beta.2 中使用 angular2)

【问题讨论】:

  • 您是否将HTTP_PROVIDERS 添加到bootstrap(AppComponent, [...])@Inject(BroadcastService) 是多余的 AFAIK。
  • 是的。我真的不知道,问题可能是什么
  • 我猜这是源文件中类的顺序。 AuthServiceBroadcastService 在同一个文件中吗?改变这两个类的顺序或者使用forwardRef

标签: angular


【解决方案1】:

似乎需要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 error:

【讨论】:

猜你喜欢
  • 2017-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多