i have been able to get controller to use the $on listener with $scope.$on
.
but i don't see any documentation on how to get services to listen for events.
I tried $rootScope.$on
, but that only allows one listener. i want listeners in multiple services regardless of whether their parent controllers are in scope or not.
The HttpClient is injected only in my-service and there is no problem at all. I hope it helps you to understand it better.
ts file. The main reason for doing this is to tell Angular that when the component is created, an instance of the service class is also created to perform all the tasks. The instance should also be declared in the providers' array of the component.
Services are a set of code that can be shared by different components of an application. So for example if you had a data component that picked data from a database, you could have it as a shared service that could be used across multiple applications.
after experimenting a fair bit it turns out that getting events to the service can be done with minimal code.
sample service code follows in case anyone else runs into this.
The sample saves and restores the service model to local storage when it gets the respective broadcasts
app.factory('userService', ['$rootScope', function ($rootScope) { var service = { model: { name: '', email: '' }, SaveState: function () { sessionStorage.userService = angular.toJson(service.model); }, RestoreState: function () { service.model = angular.fromJson(sessionStorage.userService); } } $rootScope.$on("savestate", service.SaveState); $rootScope.$on("restorestate", service.RestoreState); return service; }]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With