Answer the question
In order to leave comments, you need to log in
How to use a factory as a data store between controllers?
Hello!
I am learning angular and faced the following problem.
Different controllers use the same data, so I decided to store them in a factory.
But I can not understand why in this case the variable dbListWithTables = null is returned when the correct object is displayed in the console.
Factory code:
'use strict';
angular.module('labApp').factory('StorageFactory', ['$http', function ($http) {
var storage = {};
var err = '';
var dbList = null;
var dbListWithTables = null;
storage.getDbListWithTables = function() {
var conf = {
method: 'GET',
url: '/php/getDbInfoFull.php'
};
$http(conf).then(
function successCallback(success) {
console.log(success.data);
dbListWithTables = success.data;
},
function errorCallback(error) {
err = error.data;
}
);
return dbListWithTables;
};
return storage;
}]);
'use strict';
angular.module('labApp').controller('navCtrl', ['$scope', 'StorageFactory', function ($scope, StorageFactory) {
$scope.storage = StorageFactory;
if ($scope.dbListFull === undefined) {
$scope.dbListFull = $scope.storage.getDbListWithTables();
}
}]);
Answer the question
In order to leave comments, you need to log in
1. "factory" is a way to spawn a service. That is, you will store the data in the service. Well, such a moment - you do not store data there, but store the logic for obtaining this data.
2. read about anonymous functions, no need to specify names for callbacks
3. read about promises, this will solve your problem. Also read about the event loop in javascript, how to work with asynchronous operations, etc.
4. It is very convenient to put such things into resolvers, leaving the controllers as dumb as possible
5. components. The "independent controllers" registration approach is deprecated.
The last two points are required to study but not right now. This is if you want to learn how to do "comfortable".
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question