angularjs make json to array and use in a factory

48 Views Asked by At

This is the factory I use right now, I get 2 json objects and try to do a array of them then I cant use it in the textreplacer.

app.factory('myFactory', function ($http) {
  var service = {}
  var array =  [];
  var obj = [];


  service.getText = function () {
    return text =  $http.get('api/json_text').then(function(res){
        return res.data;
    });
  }
  service.getShortcuts = function () {
    return shortcuts = $http.get('api/json_shortcuts').then(function(res){
        return res.data;
    });
  }
  service.merchJson = function () {
    service.getText().then(function(text) {
      service.getShortcuts().then(function(shortcuts) {
        angular.forEach(text, function(value, key) {
          if(!angular.isUndefined(shortcuts[value])){
            array_value = shortcuts[value];
            obj[key] = array_value;
            array.push(obj[key]);
          }else{
            array_value = text[key].toString();
            obj[key] = array_value;
            array.push(obj[key]);
          }
        });

      });
    });
    return array;
  }
  service.textReplacer = function () {
      var array = service.merchJson();
      angular.forEach(array, function(value, key) {

      });
      console.log(array);

  }
  return service;
})

Is it something I done wrong or a bug because I can see it in console.log(array) without any problem.

1

There are 1 best solutions below

6
Rahul Sharma On

try this

service.merchJson = function () {
    var result;
    return service.getText().then(function (text) {
            result = text;
            return service.getShortcuts();
        })
        .then(function (shortcuts) {
            angular.forEach(result, function (value, key) {
                if (!angular.isUndefined(shortcuts[value])) {
                    array_value = shortcuts[value];
                    obj[key] = array_value;
                    array.push(obj[key]);
                } else {
                    array_value = result[key].toString();
                    obj[key] = array_value;
                    array.push(obj[key]);
                }
            });
            return array;
        });
}


service.textReplacer = function () {
    service.merchJson().then(function (array ) {
        angular.forEach(array, function (value, key) {});
        console.log(array);
    });
}