Bilal Bayasut
Bilal Bayasut

Reputation: 121

Cannot get the $scope.data populated from service in angular

I can't get my scope variable populated from a object resulted from a service.

here is my service :

app.factory("studentService", ['$http','$q','$localstorage','$state', 
    function($http,$q,$localstorage,$state) {

 return{
    getPersonalInfo:function(pi_id)
            {
                    return $http.get(app.baseUrlServer + app.baseUrlUser +   '/getpersonalinfo/' + pi_id)
                    .then(function(response){
                        if (response.data) {
                        
                            return response.data;
                        } else {
                            // invalid response
                            return $q.reject(response.data);
                        }
                    },function(response){
                        // invalid response
                        return $q.reject(response.data);
                    });
            }
   }
 
 /* my controller */
 var app_ctrl = angular.module('app.controllers');
app_ctrl.controller('MatesprofileController', 
	['$scope','$stateParams','studentService','$localstorage',
	function($scope, $stateParams, studentService , $localstorage) {
      
      $scope.personalInfo=[];
    
    studentService.getPersonalInfo($stateParams.pi_id).then(function(data){
	    	
	    	$scope.personalInfo.push(data);
	    	   
  		 }); 
  
    
    }

I can't get my $scope.personalInfo array populated even though I already pushed the data object into personalInfo array.

in fact, when I console.log(data) inside of the .then function, It outputs the data, but when I do the same, just outside of the .then blocks, it shows nothing..

please, help me. I'm totally stuck of this


update

I've done the following :

app.factory("studentService", ['$http', '$q', '$localstorage', '$state',
      function($http, $q, $localstorage, $state) {


        return {
          getPersonalInfo: function(pi_id) {
            var defer = $q.defer();

            $http.get(app.baseUrlServer + app.baseUrlUser + '/getpersonalinfo/' + pi_id)
              .then(function(response) {
                if (response.data) {
                  defer.resolve(response.data);
                } else {
                  // invalid response
                  defer.reject(response.data);
                }
              }, function(response) {
                // invalid response
                defer.reject("Error");
              });
            return defer.promise;

          }

        }

      }


      /* CONTROLLER */

      var app_ctrl = angular.module('app.controllers');
      app_ctrl.controller('MatesprofileController', ['$scope', '$stateParams', 'studentService', '$localstorage',
          function($scope, $stateParams, studentService, $localstorage) {

            //$scope.personalInfo=[];
            studentService.getPersonalInfo($stateParams.pi_id).then(function(data) {
              $scope.data = data;
              console.log($scope.data); //this shows up correctly, but it executed latest

            });

            console.log($scope.data); // this shows up first in the console, but it's empty
          }

Still not workgin :(

update

Finally, I get it worked by simply to not using the then() function. because the service returns the actual data instead of promise, thus, on the controller only need to call it as a variable.

example:

$scope.data = studentService.getPersonalInfo($stateParams.pi_id);

voila!, thanks for those who helped me, special thanks to my friends @arwaniali for suggesting me this solution and also all of you who have answered this questions. thanks : )

Upvotes: 0

Views: 551

Answers (2)

Yaron Schwimmer
Yaron Schwimmer

Reputation: 5357

Your getPersonalInfo is inconsistent in what it returns. If the http call is successful and you get data, you return the actual data rather than a promise. If you want your function to always return a promise, then you should change getPersonalInfo the following way:

getPersonalInfo:function(pi_id) {
    var deferred = $q.defer();
    $http.get(app.baseUrlServer + app.baseUrlUser +   '/getpersonalinfo/' + pi_id)
        .then(function(response){
            if (response.data) {
                deferred.resolve(response.data);
            } else {
               // invalid response
               deferred.reject(response.data);
            }
         },function(response){
               // invalid response
               deferred.reject("Error");
         });
    return deferred.promise; 
}

Upvotes: 1

Kmart2k1
Kmart2k1

Reputation: 563

The $http service returns a promise. You should return this promise to your controller, and then test the return data and do the appropriate error handling if necessary.

 app.controller('MatesprofileController', ['$scope','studentService', function($scope,  studentService ) {
   $scope.personalInfo=[];
      studentService.getPersonalInfo(123).then(function(data){
        if(data !== undefined && data.length > 0)
          $scope.personalInfo = data;
        else
          console.log('handle error');


        console.log($scope.personalInfo);
      });
 }]);

http://plnkr.co/edit/ZzNBT6pDqhqcAseWVX5I?p=preview

Upvotes: 0

Related Questions