首页 > 解决方案 > 另一个函数运行成功javascript后无法赋值

问题描述

我有一些这样的代码

我有加载功能,它调用testRequest功能。

testRequest函数调用ajax服务并返回响应。

但是testRequest函数运行成功后,加载函数得到未定义的值

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;
  }
}]);

请帮忙!

标签: javascriptangularjs

解决方案


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).

更多信息... $http请求角度


推荐阅读