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

查看:198
本文介绍了@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
  }

}

我将该服务注入组件:

@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.

因此解决方案是致电:

providers:[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天全站免登陆