I am defining service as class, something like this:
@Injectable()
export class MyService {
...
}
In other components or pages, I am importing that class with just import command.
import { MyService } from '../pages/services/myservice';
In constructor:
constructor(public _MyService: MyService)
In my main app.module.ts I have added that class service as provider.
providers: [someOtherThings, MyService, someOtherThings]
In Ionic 2, things are working as expected. Service is singleton.
But in Ionic 3, which uses angular 4, it looks like every component is creating new instance of that class.
Is there some new way of creating singleton services classes in angular 4?
Try storing the Service's instance in your
AppModule
and get the instance (instead of instancing it) later in other components.And to retrive the Service's instance use:
Check the documentation Here!
In my case, it have something to do with
ReflectiveInjector
.I have two services A and B, each should be a singleton service referring to each other.
If I inject them in the other's constructor, it may cause compiling error, due to circular reference.
If I use
in B's constructor, it will make another instance of A.
And is should be solved by making a CService holding the data, and AService and BService can access data through CService.
Im using ionic 3 with lazyload an angular 4 and not having the issues. To make it singleton make sure your app module provide the service. and remove providers on @Component that use the service.
App Module
The Service
Tes Case the service on ionic page
First Page
Second Page
Third Page it create new instance if providers added on component
make sure to remove the providers on component to make it singleton.