4

I am new to AngularJs. I have a situation that I need to fetch same data for multiple controller. So, I came to know to use angularJs service for this and call that service from controller.

Now, when I call this service from both of the controller, the service get hit twice. I have cached the data in service, but still the service generates two ajax request to the server.

How to handle this situation?

Aman Jain
  • 655
  • 5
  • 17
  • So....You're calling a service methods from two different locations and wondering why it's being called twice and are confused as to why it is being running twice. Is this correct? – Patrick Motard May 21 '15 at 18:26
  • Flagged as low quality, this is not an angularJS specific question but a general question of software design. – Alex C May 21 '15 at 18:28
  • Can you post your code from Service and Controllers? (make a jsfiddle, with just the relevant lines) if your concern is simply about `$http` being called twice then that may be solvable...another possible approach may be to use `promise chaining` – Shehryar Abbasi May 21 '15 at 19:49
  • I may be misunderstanding, but I believe the OP understands that a service is a singleton type, has set up a cache, but doesn't understand why the server is getting hit twice with two calls - as @Shehryar Perhaps you could post your service and controllers? – jdphenix May 21 '15 at 19:52

2 Answers2

0

Every time you call a service method, no matter where you call it from, it will be run. So if you have two controllers and you call the service method from each controller separately, the service method will run twice.

Patrick Motard
  • 2,650
  • 2
  • 14
  • 23
0

I have cached the data in service, but still the service generates two ajax request to the server.

In case you are talking about not calling the $http request twice when you inject One Service in Two Controllers:

this SO post seems to be implementing something similar perhaps:
1 Service with an $http request and 2 Controllers which consume the returned promise.

In that case, the second Controller was waiting for a broadcast event before using the Service's returned data (and not calling the $http request over again) -- See if this implementation helps with your application. GL!

Community
  • 1
  • 1
Shehryar Abbasi
  • 378
  • 2
  • 8