-1

I have some code like this

I have load function, it call testRequest function.

testRequest function call ajax service and return response.

But after testRequest function run success, load function get undefined value

angular.module('MyApp', []).controller("AppCtrl", ['AjaxService', function(ajax) {
  var l_this = this;
  this.testRequest = function() {
    var req = ajax.getstatus('https://testapi.io/api/nguyenthemanh2601/testangular');
    req.then(function(rep) {
      var arr = [];
      if (rep.status == 400) {
        for (i = 1; i < 10; i++) {
          arr.push(rep.data + i);
        }
        return arr;
      } else {
        for (i = 1; i < 10; i++) {
          arr.push(rep.data + i);
        }
        return arr;
      }
    });
  };
  this.load = function() {
    var res = l_this.testRequest();
    console.log(res);
    l_this.status = res;
  }
}]);

Please help!

Rich
  • 3,928
  • 4
  • 37
  • 66
The Manh Nguyen
  • 406
  • 6
  • 19
  • Put `return` to the req. This question was marked duplicate so I cannot post answer. – Rich Aug 06 '19 at 05:35

1 Answers1

0

angular.module('MyApp', []).controller("AppCtrl", ['AjaxService', function(ajax) {
  var l_this = this;
  this.testRequest = function() {
    $http({
      method: 'POST',
      url: 'https://testapi.io/api/nguyenthemanh2601/testangular',
    }).
    success(function(rep) {
      if (rep.status == 200) {
        for (i = 1; i < 10; i++) {
          arr.push(rep.data + i);
        }
        return arr;
      }
    }).
    error(function(rep) {
      if (rep.status == 400) {
        for (i = 1; i < 10; i++) {
          arr.push(rep.data + i);
        }
        return arr;
      }
    });
  };
  
  // Next Execution.....
}]);

Note You can handle success and error message based on that response execute the next step(handle error and success).

more info... $http request angular

Parth Raval
  • 4,097
  • 3
  • 23
  • 36