I'm new in angular and I'm working on a project that depends on service and factories. my problem is when I'm using a static jason array for response, the variables are filled correctly and are shown in view, but when I change it to a ajax request and get it from a json file, the response comes successful but the controller variables are not successfully loaded with data.
this is my angular project structure:
'use strict';
angular
.module('mytestapp',['ngRoute'])
.config(config)
.controller('HomeCtrl', HomeCtrl)
.controller('AboutCtrl', AboutCtrl)
.factory('GeneralInit', GeneralInit)
.service('UserSrv', UserSrv);
GeneralInit.$inject = ['UserSrv','$q'];
HomeCtrl.$inject = ['GeneralInit','$timeout','UserSrv'];
and here are my config:
function config($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'template/home.html',
controller: 'HomeCtrl',
controllerAs: 'hmc',
resolve: {
GeneralInit: function(GeneralInit){
return GeneralInit();
}}
})
.when('/about', {
templateUrl: 'template/about.html',
controller: 'AboutCtrl',
controllerAs: 'abc',
resolve: {
GeneralInit: function(GeneralInit){
return GeneralInit();
}}
});
}
here is my service:
function UserSrv($http) {
var User={};
var service = {
getUser: Get,
updateUser: Update,
logoutUser: Logout
};
return service;
function Get() {
//return {"FirstName":"StaticName","LastName":'StaticLastName'}
$http.get('/user.json')
.success(function(data, status, headers, config) {
User = data;
console.log(User);
return User;
})
.error(function(data, status, headers, config) {
})
}
function Update() {
}
function Logout() {
}
}
My controller and initialize item:
function GeneralInit(UserSrv,$q)
{
return function() {
var User = UserSrv.getUser(); //{'FirstName':'FstName','LastName':'LstName'};//
var Base='browser';
return $q.all([User, Base]).then(function(results){
return {
User: results[0],
Base: results[1]
};
});
}
}
function HomeCtrl(GeneralInit,$timeout)
{
var hmc= this;
$timeout(function(){
hmc.User=GeneralInit.User;
console.log(hmc.User);
}
,0);
}
The reason why you don't see any data in the console.log(hmc.User);
statement is because by the time this statement executes, the promise is not actually resolved (the request fetching users has not yet returned). Though digest cycle is invoked as a result of using $timeout
, hmc.User
does not have data yet.
Try invoking the digest cycle after the requests actually return in your GeneralInit
method, and you should have the data available.
And also you should probably change your Get method to return a promise:
function UserSrv($http) {
var User = {};
var service = {
getUser: Get
};
return service;
function Get() {
return $http.get('/user.json')
.success(function(data, status, headers, config) {
User = data;
console.log(User);
return User;
})
.error(function(data, status, headers, config) {
})
}
}