0

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);
}
1
  • How can you expect to capture "User" and "Base" variables using promise resolved then function. You have to run a call back inside then callback to update your controller. Commented Jul 13, 2015 at 13:58

2 Answers 2

1

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) {

      })
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Your GeneralInit function is expecting getUser to return a promise, so just change it to this:

function UserSrv($http, $q) {
  var User={};
  var service = {
    getUser: Get,
    updateUser: Update,
    logoutUser: Logout
  };
  return service;

  function Get() {
    var deferred = $q.defer();
    //return {"FirstName":"StaticName","LastName":'StaticLastName'}
    $http.get('/user.json')
      .success(function(data, status, headers, config) {
          User = data;
          console.log(User);
          deferred.resolve(user);
          return User;
      })
      .error(function(data, status, headers, config) {

      });
      return deferred.promise;
  }
}

1 Comment

not tested but I think that if you return $http.get(etc, etc) you can have the same results without creating a promise

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.