@Injectable 服务似乎不是单例 [英] @Injectable service does not seem to be a singleton

查看:31
本文介绍了@Injectable 服务似乎不是单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 Angular 服务:

I have an Angular service like so:

@Injectable
export class MyService {

  foo = true;

  fireTheCallback(){
    assert(this.foo === true); // this is correct
    this.cb();   // this.cb is not defined
  }

}

我将该服务注入到一个组件中:

I inject that service into a component:

@Component({providers:[MyService]})
export class MyComponent {

 constructor(data: MyService){
     data.cb = v => {
        // attach this callback function to the service
     }
 }

}

服务创建后,我们调用了fireTheCallback(),但是没有定义this.cb.不是上下文绑定不当的问题,因为其他变量如 foo 设置正确.问题似乎是重新创建了服务,因此 this.cb 值丢失了.

after the service is created, we call fireTheCallback() but this.cb is not defined. It's not an issue of impromper context binding, because other variables like foo are set correctly. The problem appears to be that the Service gets recreated, so this.cb value gets lost.

有谁知道为什么会发生这种情况?我认为由@Injectable 标记的服务是单身......这里发生了什么.

Does anyone know why this might happen? I thought Services marked by @Injectable were singletons...what is going on here.

推荐答案

好吧,之所以有不止一个类的实例,是因为我用的是providers:[MyService]不止一处.

Ok, so the reason why there was more than one instance of the class, was because I was using providers:[MyService] in more than one place.

所以解决方案是调用:

提供者:[MyService]

只要一次,如果您希望 MyService 成为单例(您只需要该类的一个实例.最好让提供程序在您的根模块中调用.

just once, if you want MyService to be a singleton (you want only one instance of that class. best to make the providers call in your root module.

因此,您应该根据需要多次调用 @Inject(MyService),这将在任何地方注入相同的单例.

So you should call @Inject(MyService) as many times as you want, that will inject the same singleton everywhere.

这篇关于@Injectable 服务似乎不是单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆