简体   繁体   中英

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.

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

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! You should use the internet explorer as the browser.

I hope this helps : http://enable-cors.org/

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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