I have a controller which manages I page of data and a service which makes an HTTP request every 30 seconds to get fresh data to show on the page. I'm trying to write this in an "Angular" way that is testable and leverages the service properly.
I can think of two basic approaches, and I'm guessing one (or maybe both) is wrong:
The controller stores the data in a $scope variable, and does a
setInterval
or$timeout
to call methods of the service to get new data and then update the variable.The service stores the data in it's own variables/property and periodically calls its self to get new data. And the controller somehow watches/listens to the service properties to know when to update the view.
For the purposes of this question, it may be helpful to consider a concrete example. If the HTTP request fails, I want to show the error to the view/user. So assume an errorMsg
variable that needs to live somewhere. Should it live in the controller? In which case, the service needs to return that value every time. Or should it live in the service, and the controller somehow watches for it.
I've tried the first approach, and it seems to result in a LOT of logic in the controller, mostly in then()
s which follow the service methods. My instinct is that #2 is the correct way to do it. But I'm a little unclear as to how the controller should listen/watch the service. Thanks in advance.