gpt4 book ai didi

typescript - 点击功能中的angular2访问依赖

转载 作者:搜寻专家 更新时间:2023-10-30 21:24:42 27 4
gpt4 key购买 nike

我正在使用 angular2/Typescript 构建应用程序,并尝试访问作为依赖项注入(inject)的服务。在 Angular 1.x 中,我会通过 Controller 函数访问此服务,并且所有子函数都能够访问相同的依赖项。在这里,我通过组件的构造函数注入(inject)它,如下所示:

   constructor( @Inject(JRummy) rummyGame: JRummy) {

this.currentGame = new Game();
rummyGame.startGame(this.currentGame);

}

其中 rummyGame 是我尝试注入(inject)的服务。这工作正常。但是,在构造函数中访问了这个服务之后,如何在其他函数中访问它呢?例如,我在组件中有以下点击功能,我想在其中调用 rummyGame 服务中的方法:

  simulateComputer():void {

rummyGame.computerPlaySolo();

}

如果 rummyGame 服务刚刚注入(inject)到构造函数中,它如何注入(inject)到这个点击函数中?我是否需要在组件上创建一个属性来存储构造函数访问该服务的实例?

最佳答案

更简单的方法是将变量声明为 private,这样它就可以直接在类的上下文 (this) 中使用。

constructor( @Inject(JRummy) private rummyGame: JRummy) {

//code here

}
//do access service object by having this.rummyGame
simulateComputer():void {
this.rummyGame.computerPlaySolo();
}

另一件事是你需要在你的服务类上使用 @Injectable 装饰器,以使其作为依赖项在其他组件构造函数中 injectable

关于typescript - 点击功能中的angular2访问依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36960037/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com