How to store data from http service in angular factory

I would like to save the value from /api/login.json globally using the service, but I think I have some kind of problem. The console.log statement in the controller tells me that the scope.login object is undefined.

What am I missing?

Thanks!

Factory service:

myApp.factory('LoginFactory', ['$http', function($http){ this.data; $http.get('/api/login.json').success(function(data) { this.data = data; }); return { getData : function(){ return this.data; } } }]); 

Controller:

 myApp.controller('AccountsCtrl', ['$scope', 'Accounts', 'LoginFactory', function($scope, Accounts, LoginFactory){ $scope.login = LoginFactory.getData(); console.log('$scope.login: %o', $scope.login); $scope.accounts = Accounts.index(); }]); 
+6
source share
3 answers

you should avoid using the this in this context. it's better to just declare a new variable.

 myApp.factory('LoginFactory', ['$http', function ($http) { var data; $http.get('/api/login.json').success(function (d) { data = d; }); return { getData: function () { return data; } }; }]); 

you will still have a race problem, so I would also recommend with both chains

 myApp.factory('LoginFactory', ['$http', function ($http) { var promise = $http.get('/api/login.json'); return { getData: function (callback) { promise.success(callback); } }; }]); 

or even conditional get

 myApp.factory('LoginFactory', ['$http', function ($http) { var data; return { getData: function (callback) { if(data) { callback(data); } else { $http.get('/api/login.json').success(function(d) { callback(data = d); }); } } }; }]); 

The last two approaches require you to rewrite your controller, but

 myApp.controller('AccountsCtrl', ['$scope', 'Accounts', 'LoginFactory', function($scope, Accounts, LoginFactory){ LoginFactory.getData(function(data) { $scope.login = data; console.log('$scope.login: %o', $scope.login); $scope.accounts = Accounts.index(); //this might have to go here idk }); }]); 
+8
source

Answer extension @LoganMurphy. Using promises and adding callbacks is not at all desirable. The best way to write a service might be

 myApp.factory('LoginFactory', ['$http', function ($http, $q) { var data; return { getData: function () { if(data) { return $q.when(data); } else { return $http.get('/api/login.json').then(function(response){ data = response; return data; }); } } }; }]); 
+3
source

You have a problem with the this , and also you are not keeping the promise with http.get correctly

I would write this as follows:

 myApp.factory('LoginFactory', ['$http', function($http){ return { getData : function(){ return $http.get('/api/login.json'); } } }]); myApp.controller('AccountsCtrl', ['$scope', 'Accounts', 'LoginFactory', function($scope, Accounts, LoginFactory){ $scope.login = LoginFactory.getData().success(function(data){ console.log(data); console.log('$scope.login: %o', $scope.login); }); }]); 
0
source

Source: https://habr.com/ru/post/979349/


All Articles