Search code examples
javascriptangularjsinheritanceangularjs-service

AngularJS $scope inheritance service


I'm having some trouble with my code. I can't pass nor console.log the inherited $scope.user in my data service. As I'm having this problem also in another situation which looks the same I guess it's because of the callback.

The main Controller creates the user

 .controller('mainCtrl', function ($scope, dataService) {
    dataService.getUser(function (response) {
        $scope.user = response.data[0];
    })

The dataservice

    .service('dataService', function ($http) {
    this.getUser = function (callback) {
        $http.get('mock/user.json')
            .then(callback)
    };

The navigation controller (child of mainCtrl):

    .controller('navCtrl', function ($scope, dataService) {
    //$scope.user = "test";
    console.log ($scope.user);
    dataService.getNavItems($scope.user,function (response) {
        $scope.navItems = response.data;
    });

As you can guess if I set $scope.user manually it works just fine.


Solution

  • The promise hasn't resolved yet when navCtrl is instantiated. What you can do is return the promise from $http.get instead of setting scope.user directly in the callback. And then just wrap the call to getNavItems in the promise.

    This is assuming, navCtrl is a child of MainCtrl

    .service('dataService', function ($http) {
      this.getUser = function () {
        return $http.get('mock/user.json');
      }};
    
    .controller('mainCtrl', function ($scope, dataService) {
        $scope.userPromise = dataService.getUser();
     })
    
    .controller('navCtrl', function ($scope, dataService) {
      $scope.userPromise.then(function(response) {
       var user = response.data[0];
       dataService.getNavItems(user, function (response) {
           $scope.navItems = response.data;
       });
    });
    

    })