简体   繁体   English

Cordova / AngularJS工厂GET JSON XMLHttpRequest

[英]Cordova/AngularJS factory GET JSON XMLHttpRequest

I've been trying to fetch a JSON from an api with a XMLHttpRequest inside a factory but it ends up returning undefined even though the logging inside it suggest that it should work just fine. 我一直在尝试从带有工厂内部XMLHttpRequest的api中获取JSON,但是即使它内部的日志表明它应该可以正常工作,它也会返回未定义的结果。

Here is my factory code 这是我的工厂代码

.factory('MyService', function(){
return {
    getJSON: function(path){
      var xhr = new XMLHttpRequest();
      xhr.open("Get", path, true);
      xhr.onreadystatechange = function(){
        if(xhr.readyState === 4){
          if(xhr.status === 200){
            console.log(JSON.parse(xhr.responseText)); // Displays a correct JSON object
            return JSON.parse(xhr.responseText); // Returns said object
          }else{
            return xhr;
          }
        }
      };
      xhr.send();
      }
    }
})

Here I call the service from my controller 在这里,我从控制器呼叫服务

$scope.test = MyService.getJSON("api url"); // Ends up as undefined

the console.log inside the factory triggers and displays the JSON correctly, how ever $scope.test ends up being undefined even though we return the exact same JSON to the $scope.test 工厂内的console.log会触发并正确显示JSON,即使我们将完全相同的JSON返回到$ scope.test,但$ scope.test最终还是未定义

If anybody has any idea why this isn't working, that would be great, thank you 如果有人知道为什么它不起作用,那太好了,谢谢

It is because of the cross domain call you are doing. 这是因为您正在执行跨域调用。 Either enable the cross origin call or do a normal http-promise! 启用跨源调用或执行常规的http-promise! You should use the internet explorer as the browser. 您应该使用Internet Explorer作为浏览器。

I hope this helps : http://enable-cors.org/ 希望对您有所帮助: http : //enable-cors.org/

  1. https://docs.angularjs.org/api/ng/service/ $http https://docs.angularjs.org/api/ng/service/ $ http

可能在半年前就解决了这个问题,问题是工厂没有返回承诺,而是在使用$ q将其变为承诺后,工厂开始按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM