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);
}