Service get called multiple time if child component selector is used multiple time in parent component

Viewed 177

I am facing the problem in which, the service is getting called multiple times.

I have used same child component selector two time in parent component.

The service I have written in ngOnInit() only single time.

Ideally, If I have written service in ngOnInit, it should be called once on page load.

but It is getting called 3 times.

1 time ngonInit and 2 time for two selector.

I have not called the service in any lifecycle except ngOnInit.

1 Answers

@Raman, I am not sure what that service does but I think both child and parent component need the result from service while page loading.

In this case service get call multiple times that is the expected behavior in Angular as @Baris said.

You can do one thing, if you really required to use that service result in somewhere in your parent component then create a one more new component and use that service in newly added component. Now you can add this new component in parent component so while page load service will call in newly added child component not in parent so that each child component can call service from their page/file. This solution may help you.

Related