Reputation: 357
I need to use a component in two different modules, the component is using a service that has a certain state. the component also has child components that use the same service. I need two instances of the service because I don't want the actions in the component in module 1 to affect the state of the service in module two.
My current solution is that I inject the service in the component decorator and by that scope the service to the component instance. and I am passing this specific instance to the child components as @input
field.
Is there a better solution?
Upvotes: 1
Views: 1070
Reputation: 3243
Few suggestions,
in your case you want different search result based on components, so you can create a common service which can take some params and fetch you result.
All the best
Upvotes: 0
Reputation: 2817
I would create an abstract class and extend it in components, you i would create new comps for every page.
export abstract class Base{
constructor(protected service:any){}
}
export class Comp1 extends Base{
constructor(protected service: Service1){
super(service);
}
}
export class Comp2 extends Base{
constructor(protected service: Service2){
super(service);
}
}
This way you have to write your codes only once and it is very flexible to override anything in case you have to.
Upvotes: 1
Reputation: 8690
I'm assuming what you are looking for is a non-singleton service. Adding your service to the providers
of your app.module.ts
makes the service a singleton service, meaning only one instance of the service will be created which will live as long as your application does. You can instead add the service in the component making it a non-singleton service.
@Component({
selector: 'app-home',
providers: [SearchService]
})
This way when Angular destroys the component, it will also destroy the service. Non-singletons services also have the ngOnDestroy()
lifecycle hook so make sure you unsubscribe your subscriptions to avoid any leakage of memory.
Upvotes: 0