Reputation:
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.
Upvotes: 0
Views: 906
Reputation:
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.
Upvotes: 1