Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i use $on in a service in angular?

Tags:

angularjs

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.

like image 542
Anton Avatar asked May 10 '13 07:05

Anton


People also ask

Where do you inject HttpClient in service file?

The HttpClient is injected only in my-service and there is no problem at all. I hope it helps you to understand it better.

What is the use of service TS file in Angular?

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.

What is correct for services in Angular?

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.


1 Answers

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; }]); 
like image 131
Anton Avatar answered Oct 02 '22 14:10

Anton