Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/411.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript angularJS闭包导致$HTTP.get不返回我的JSON对象数组_Javascript_Arrays_Angularjs_Json - Fatal编程技术网

Javascript angularJS闭包导致$HTTP.get不返回我的JSON对象数组

Javascript angularJS闭包导致$HTTP.get不返回我的JSON对象数组,javascript,arrays,angularjs,json,Javascript,Arrays,Angularjs,Json,我的模块中有以下3种方法。factory dataservice我使用的是Angular 1.5 getCannedJSON。此函数按预期工作,我希望其他函数也能以同样的方式工作。我在postman中复制并粘贴了从webAPI获得的JSON,并将其放入函数中。它返回我想要的对象数组 getDataFromAPI。由于某些原因,我无法让此函数返回响应。log(response)正好包含我想要的数据,即与getCannedJSON相同的数据。相反,它返回一个d{$$State:object}您知道

我的模块中有以下3种方法。factory dataservice我使用的是Angular 1.5

  • getCannedJSON。此函数按预期工作,我希望其他函数也能以同样的方式工作。我在postman中复制并粘贴了从webAPI获得的JSON,并将其放入函数中。它返回我想要的对象数组
  • getDataFromAPI。由于某些原因,我无法让此函数返回响应。log(response)正好包含我想要的数据,即与getCannedJSON相同的数据。相反,它返回一个d{$$State:object}您知道我如何修改这段代码以使其以与getCannedJson方法相同的格式返回吗?
    • GetDataFromApiWithDynamicCurl这与上面的方法没有什么不同,但它将为web api提供动态url。如果不返回json对象的数组列表,则返回相同的$$State对象,则工作正常
我希望getDataFromAPI像getCannedJson一样返回json请求中所有对象的相同数组。知道我在哪里搞砸了吗。下面是他们通过console.log返回的两种不同类型对象的屏幕截图。我希望底部的数据看起来像顶部的数据

数据服务模块工厂的代码如下所示

(function (module) {
'use strict';

DataService.$inject = ['$http', '$q'];

function DataService($http, $q) {
    var getDataFromAPI = function () {
        var returnthis; 
        return $http({ //this top level returns instead 
            url: "http://localhost:34183/api/quality/month",
            dataType: 'json',
            method: 'GET',
        }).success(function (response) {
            console.log("This Response shown below is pefect! but it wont return....");  
            console.log(response);
            return (response);//This never returns
        }).error(function(error){
            console.log(error);
        });
        return returnthis;
    };
    var getDataFromApiWithDynamicUrl = function (pathurl) { // this is version 2 of the method i want to work where i can dynamically change the url to the path
        return $http.get(pathurl);
    };
    var getCannedJSON = function ($http) {
        return [{
                  "hockeyTeam": "Sharks",
                  "PlayoffRecord": {
                      "wins": "0"
                  },
              },
              {
                  "hockeyTeam": "Pengiuns",
                  "PlayoffRecord": {
                      "wins": "1"
                  },
              }
        ];
    };
    return {
        getDataFromAPI: getDataFromAPI,
        getDataFromApiWithDynamicUrl: getDataFromApiWithDynamicUrl,
        getCannedJSON: getCannedJSON
    };
}
module.factory('DataService', DataService);
})(angular.module('MyCoolModule'));
下面是我调用这些方法以使用控制器中JSON数据的代码

(function (module) {
'use strict';

hockeyViewController.$inject = ['DataService'];
function hockeyViewController(DataService) {
    var vm = this;

    vm.headers = [
        { name: 'Hockey Team', key: 'hockeyTeam' },
        { name: 'Record', key: 'PlayoffRecord'}
    ];

    vm.cannedData = angular.copy(DataService.getCannedJSON());
    vm.getDataFromAPI = DataService.getDataFromAPI();
    vm.getDataFromAPIwithCustomURL = [];
    DataService.getDataFromApiWithDynamicUrl("http://localhost:34183/api/quality/month").then(function(response){
        console.log("this response should work - and it does it in the right format");
        console.log(response.data);// this looks perfect
        vm.getDataFromAPIwithCustomURL = response.data;
        return response.data;
    }, function (error) {
        console.log(error);
    });
    vm.testMonthResults2 = angular.copy(DataService.getDataFromApiWithDynamicUrl("http://localhost:34183/api/quality/month"));

    console.log("canned json Data- works great"); 
    console.log(vm.cannedData);// this works perfectly  
    console.log("this is the data results with dynamic url - returns wrong object the $$state ");
    console.log(vm.getDataFromAPI);// returns $$state not array of objects
    console.log(vm.getDataFromAPIwithCustomURL); // this returns [] which is wrong
    console.log(DataService.getDataFromApiWithDynamicUrl("http://localhost:34183/api/quality/month"));
    // this doesnt work either 
}
function reportTabularViewDirective() {
    return {
        restrict: "E",
        controller: hockeyViewController,
        controllerAs: 'vm',
        bindToController: true,
        scope: {
        },
        templateUrl: "app/widgets/hockey-view.html"
    };
}

module.directive('hockeyView', hockeyViewDirective);

})(angular.module('MyCoolModule'))

通过调用
DataService.getDataFromAPI()
可以获得$promise对象。您需要处理$PROMITE对象才能获得响应

DataService.getDataFromAPI().then(function(response) {
    // console.log(response);
})
这同样适用于
getDataFromApiWithDynamicCurl()
函数

有关更多信息,请参阅文档:


你可以试试这个

var getDataFromAPI = function () {
        return $http({
            url: "/api/quality/month", // try using relative path
            dataType: 'json',
            method: 'GET',
           }).then(function(response) {
              console.log(response);
              return respose.data;
           }, function(error) {
              console.log(error);
              return [];
          });
 };
但最好使用这样的方法:仅服务返回
承诺
,在控制器中使用
然后
函数来处理响应

在职:

var getDataFromAPI = function() {
     return $http.get('/api/quality/month');
};
在控制器中:

DataService.getDataFromAPI().then(function(response) {
    console.log(response.data);
}, function(error) {
    console.log(error);
});

我相信你需要推迟结果:就个人而言,我对所有http请求都使用.then(…)方法,而不是成功(…)和错误(…)我有点理解应该如何使用.then方法而不是成功,但是我仍然没有正确地实现它。两者都没有改变任何事情。有没有可能我遗漏了什么。对于上面的示例,我是否还需要一个。然后在控制器中?问题是您在得到响应之前返回了
returnthis
。第一个过程不需要使用
然后使用
。然而,在我的第二个过程中,
响应
错误
显示了什么值?我得到了相同的{$$state:Object}$$status:Objectstatus:0_____________________:Object有人否决了这个问题和原始问题。我真希望他们会说些没道理的话。那么,我可能需要在?在控制器中?您可以演示如何从控制器调用吗?你能检查一下你的服务器端是否收到了这个函数的调用并返回了有效的信息吗?最好将它命名为$q promise object
$promise
在角度上下文中可能指的是
$resource
promise,这里不是这种情况。