0

I'm trying to share data via a service that uses the $HTTP function between controllers. I'm trying to pass the return data in SUCCESS to another controller. Something is wrong I think in the service the data doesn't get to the second controller. below is my code can someone take a look at it and tell me what I'm doing wrong point me to the right direction on what to do.

services.js

.factory('userService', function ($http) {
    var url = "url.php";
    var headers = {
        'Content-Type' : 'application/x-www-form-urlencoded; charset-UTF-8'
    };
    var params = "";
    return {

        getUsers : function (entry, searchTypReturn) {
            params = {
                entry : entry,
                type : searchTypReturn,
                mySecretCode : 'e8a53543fab6f5e'
            };

            return $http({
                method : 'POST',
                url : 'https://servicemobile.mlgw.org/mobile/phone/phone_json.php',
                headers : {
                    'Content-Type' : 'application/x-www-form-urlencoded; charset-UTF-8'
                },
                transformRequest : function (obj) {
                    var str = [];
                    for (var p in obj)
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    return str.join("&");
                },
                data : params
            })
            .success(function (data, status, headers, config) {

                return data;

            });

        }
    }
})

controller.js

.controller('phoneController', function ($scope, md5, $http, userService, $ionicLoading, $location, $ionicPopup) {

    userService.getUsers(form.entryText, searchTypReturn).success(function (data, status, headers, config) {
        $ionicLoading.hide();
        $scope.name = data.PlaceDetailsResponse.results[0].first_name;
        if ($scope.name == 0) {
            $scope.showAlert();

        } else {

            $location.path('phoneView');
            $ionicLoading.hide();
        }
    }).error(function (data, status, headers, config) {
        $scope.showAlert();
        $ionicLoading.hide();
    })

});

.controller('phoneViewController', function ($scope, userService) {
    $scope.input = userService;
    console.log('This is from phoneView', $scope.input);
});
9
  • do you need to pass received data from API in a controller to another controller? Commented Feb 9, 2016 at 14:40
  • you can't return in success, there is nothing to return to. Use then() to return data from promise object Commented Feb 9, 2016 at 14:45
  • @NasserGhiasi yes, that's what I'm trying to do. Commented Feb 9, 2016 at 14:49
  • you can not return $http but you can use callback in your service! Commented Feb 9, 2016 at 14:54
  • I think I have your answer, but I think you need to set data in $rootScope inside userService.getUsers success callback method! give me more information Commented Feb 9, 2016 at 15:05

2 Answers 2

1

Nasser's answer is the correct one. There are other ways of keeping track of things in memory if it is just session based.

For example there is http://lokijs.org/ which also claims that the data persist between sessions because it is written to a file as well. And it replaces SQLite.

The relationship between the controllers and the directives which get the data to be displayed from the scope of the directives are loosely coupled.

If there are no values to be displayed in the scope like {{valuetobedisplayedfromcontroller}} your html becomes funky.

There are 2 options to fix this. Either use ng-if conditionals in the html directives or encapsulate the whole controller in an if command which checks a global variable to see if the data is loaded and show a loading screen and prevent user input and return error with a timeout.

I'm very keen to learn if there are other/better solutions.

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

Comments

0

you can store received data from API in $rootScope or global var or you can store data in a factory.

example for using $rootScope

angularApp.controller('phoneController', function($scope, md5, $http, userService, $rootScope, $ionicLoading, $location, $ionicPopup) {

$rootScope.data = userService.getUsers(form.entryText,searchTypReturn).success(function(data, status, headers, config) {
    $ionicLoading.hide();
    $scope.name = data.PlaceDetailsResponse.results[0].first_name;
    if ($scope.name == 0) {
            $scope.showAlert();

    } else {

        $location.path('phoneView');
        $ionicLoading.hide();
    }
 }).error(function(data, status, headers, config) {
    $scope.showAlert();
    $ionicLoading.hide();
})

}
});

.controller('phoneViewController', function($scope,$rootScope) {
$scope.input = $rootScope.data;
console.log('This is from phoneView',$scope.input);
})

using data factory (Recommended)

angularApp.factory('appDataStorage', function () {
var data_store = [];

return {
    get: function (key) {
        //You could also return specific attribute of the form data instead
        //of the entire data
        if (typeof data_store[key] == 'undefined' || data_store[key].length == 0) {
            return [];
        } else {
            return data_store[key];
        }

    },
    set: function (key, data) {
        //You could also set specific attribute of the form data instead
        if (data_store[key] = data) {
            return true;
        }
    },
    unset: function (key) {
        //To be called when the data stored needs to be discarded
        data_store[key] = {};
    },
    isSet: function (key) {
        if (typeof data_store[key] == 'undefined' || data_store[key].length == 0) {
          return false;
        }else {
            return true;
        }
    }
};
});

  angularApp.controller('phoneController', function($scope, md5, $http, userService, $rootScope, $ionicLoading, $location, $ionicPopup , appDataStorage) {

var data = userService.getUsers(form.entryText,searchTypReturn).success(function(data, status, headers, config) {
    $ionicLoading.hide();
    $scope.name = data.PlaceDetailsResponse.results[0].first_name;
    if ($scope.name == 0) {
            $scope.showAlert();

    } else {

        $location.path('phoneView');
        $ionicLoading.hide();
    }
 }).error(function(data, status, headers, config) {
    $scope.showAlert();
    $ionicLoading.hide();
});

appDataStorage.set('key1',data);

}
});

angularApp.controller('phoneViewController', function($scope,$rootScope,appDataStorage) {
$scope.input = appDataStorage.get('key1');
console.log('This is from phoneView',$scope.input);
})

Comments

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.