Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read a variable inside service in angularjs?

I want to know how can I get the value of a variable that is inside a service, I have the following code:

myModule.service('notify', ['$window', function(win) {  
       var msgs = []; // I want to read this variable
       this.message = function(msg) {
         msgs.push(msg);
         if (msgs.length == 3) {
           win.alert(msgs.join("\n"));
           msgs = [];
         }
       };
     }]);

and I want to read the msgs variable from a controller.

like image 978
fablexis Avatar asked Jan 08 '23 11:01

fablexis


1 Answers

Declaring variables with var makes them local to the scope of the function. If you want to expose it you can store it on the object itself.

myModule.service('notify', ['$window', function(win) {  
   this.msgs = []; // I want to read this variable
   this.message = function(msg) {
     this.msgs.push(msg);
     if (this.msgs.length == 3) {
       win.alert(this.msgs.join("\n"));
       this.msgs = [];
     }
   };
 }]);

Then you can retrieve msgs on your service by reading

service.msgs

A better pattern would be to create a getter method to retrieve the messages.

myModule.service('notify', ['$window', function(win) {  
   var msgs = []; // I want to read this variable
   this.getMessages = function () {
     return msgs;
   };
   this.message = function(msg) {
     msgs.push(msg);
     if (msgs.length == 3) {
       win.alert(msgs.join("\n"));
       msgs = [];
     }
   };
 }]);

Then you can retrieve your messages by calling

service.getMessages();
like image 55
Hampus Avatar answered Jan 19 '23 07:01

Hampus