0

I'm trying to get data from database and assign it to a dynamic scope variable with a function but it doesn't assign the data to the dynamic variable at first attempt. Can anyone help?

This is my dynamicScope function;

$scope.dynamicScope= function(name, data){
  var modelScope = $parse(name);
  modelScope.assign($rootScope, data);
};

and here is postService function;

$scope.postService = function(scopeName, sentData){
    $http.post($scope.serviceLink, sentData)
            .success(function (data, status) {
              console.log("Fetched data: " + data);
              $scope.dynamicScope(scopeName, data);
            })
            .error(function (errData, status) {
               console.log("Error: "+errData);
            });
};

When I call postService as

$scope.postService("userInfo", loginData);

It prints data from the postService but it gives an error when I want to print it after the previous line like here console.log($scope.userInfo[0].user_name); it says $scope.userInfo is undefined. But it fetches previous data in the second attempt. Thanks in advance.

  • The `.success` method had been [removed from the AngularJS framework](https://stackoverflow.com/questions/35329384/why-are-angularjs-http-success-error-methods-deprecated-removed-from-v1-6/35331339#35331339). – georgeawg Sep 15 '19 at 19:24

1 Answers1

0

Return the $http promise to the function:

$scope.postService = function(scopeName, sentData){
    ͟r͟e͟t͟u͟r͟n͟ $http.post($scope.serviceLink, sentData)
            .then(function (response) {
              var data = response.data;
              console.log("Fetched data: " + data);
              $scope.dynamicScope(scopeName, data);
              return response.data;
            })
            .catch(function (response) {
               var errData = response.data;
               console.log("Error: "+errData);
               throw response;
            });
};

Then use that promise to delay the console.log:

var promise = $scope.postService("userInfo", loginData);
promise.then(function(data) {
    console.log(data);
    console.log($scope.userInfo[0].user_name);
});
georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • Thank you for your answer but it still doesn't work it says `TypeError: Cannot read property 'then' of undefined` so it means `$scope.loginData` can not be assigned to `$scope.userInfo`. – VOLKAN BAKIR Sep 15 '19 at 17:44
  • Be sure to ͟r͟e͟t͟u͟r͟n͟ the `$http.post` to the `postService` function. See update to answer. – georgeawg Sep 15 '19 at 19:23