0

I have a function to get data from the server through $http.Get method. after received the data I need to use it on another function. can anyone help me how can I use the data.

var app = angular.module("app", []);
    app.factory('itemsFactory', function ($http) {
        var factory = {};
        factory.getItems = function () {
            return $http.get('.//davidstrans.json')
        };
        return factory;
    });
    app.controller('UsersTransController', function ($scope, itemsFactory) {
        itemsFactory.getItems().success(function (data) {
            $scope.users = data;
        });});

After that I have a function for dynamically get the types:

function groupBy(arr, key) {
            var newArr = []
                , types = {}
                , newItem, i, j, cur;
            for (i = 0, j = arr.length; i < j; i++) {
                cur = arr[i];
                if (!(cur[key] in types)) {
                    types[cur[key]] = {
                        type: cur[key]
                        , data: []
                    };
                    newArr.push(types[cur[key]]);
                }
                types[cur[key]].data.push(cur);
            }
            return newArr;
        };

for this function I have to use the $scope.users=data; value. Can anyone help me? thanks in advance.

danwellman
  • 9,068
  • 8
  • 60
  • 88
KK SK
  • 91
  • 1
  • 2
  • 11
  • How about `$scope.groupedUsers = groupBy($scope.users, 'myKey');`? Just remember to call it within your promise callback or the `$scope.users` variable wont be defined. And use `then(..)` instead of `success` since the latter has been deprecated. – Nikolaj Dam Larsen Oct 12 '17 at 10:40

1 Answers1

-1

Please make changes accordingly in your code :

var app = angular.module("app", []);
app.factory('itemsFactory', function ($http) {
    var factory = {};
    factory.getItems = function (successCallBack,errorCallBack) {
       $http({
  method: 'GET',
  url: './/davidstrans.json'
}).then(function(response) {
    // this callback will be called asynchronously
    // when the response is available
           successCallBack(response);
  }, function(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
           errorCallBack(response);
  });
    };
    return factory;
});

and in app.controller :

  app.controller('UsersTransController', function ($scope, itemsFactory) {
var successCallBack = function(data){
     $scope.users = data;
}
var errorCallBack = function (data){
   //if you want to show any error 
}
  itemsFactory.getItems(successCallBack, errorCallBack);
});
vertika
  • 1,284
  • 1
  • 8
  • 22
  • This is an anti-pattern. Please don't pass callbacks around like this. What the OP already does with `return $http.get('.//davidstrans.json')` is perfectly fine - in fact it's probably the best way to could do it. – Nikolaj Dam Larsen Oct 12 '17 at 10:43