@Injectable service does not seem to be a singleton

你离开我真会死。 提交于 2019-12-11 17:52:36

问题


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
     }
 }

}

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.

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


回答1:


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.

So the solution is to call:

providers:[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.

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



来源:https://stackoverflow.com/questions/48143639/injectable-service-does-not-seem-to-be-a-singleton

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!