如何将AJAX $ http调用转换为Angular.JS

时间:2022-03-14 12:13:24

For a functionality that I need, I found a really nice AJAX example. Basically it calls the Yahoo API. But I'm working with Angular.JS. So I have no clue how to convert that. Any help?

对于我需要的功能,我发现了一个非常好的AJAX示例。基本上它调用了Yahoo API。但我正在与Angular.JS合作。所以我不知道如何转换它。有帮助吗?

That's the AJAX function (details see this posting and this JsFiddle):

这是AJAX功能(详情见这篇文章和这个JsFiddle):

 $.ajax({
        type: 'GET',
        dataType: 'jsonp',
        jsonp: 'callback',
        jsonpCallback: 'YAHOO.Finance.SymbolSuggest.ssCallback',
        data:{
            query: request.term
        },
        url: 'http://autoc.finance.yahoo.com/autoc',
        success: function (data) {
            alert("yes");
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });

So what I'm looking for, is how to convert the code above into somewhat like this. The sample should just print the return value. See this JsFiddle. Especially, I have not idea what to do with the jsonpCallback parameter. That's what I could not find in any other example.

所以我正在寻找的是如何将上面的代码转换成这样的。样本应该只打印返回值。看到这个JsFiddle。特别是,我不知道如何处理jsonpCallback参数。这是我在其他任何例子中都找不到的。

<div ng-app='MyModule' ng-controller='DefaultCtrl'>
    {{ test() }}
</div>

JavaScript

JavaScript的

function DefaultCtrl($scope, myService) {
    $scope.test = myService.test;
}

angular.module('MyModule', [])
    .factory('myService', function () {
        return {
            test: function () {

                $http.get("?????")

                .success(function(data, status, headers, config) {
                    return data;
                    })
                .error(function(data, status, headers, config) {
                    return "there was an error";
                })
            }
        }
    });

The intermediate solution - after all your help - looks like this. Thanks. I had to install a Chrome extension which allows cross-domain calls as long as you use the updated JsFiddle. I changed the way I'm passing the parameters to the http-get call and I also included the $q (promise) handling. The result contains a valid list from Yahoo YQL API. Just need to handle that array then.

中间解决方案 - 在你所有的帮助之后 - 看起来像这样。谢谢。我必须安装Chrome扩展程序,只要您使用更新的JsFiddle,就可以进行跨域调用。我改变了将参数传递给http-get调用的方式,并且还包含了$ q(promise)处理。结果包含来自Yahoo YQL API的有效列表。只需要处理该数组。

function DefaultCtrl($log, $scope, $http, myService) {

    var promise = myService.getSuggestions('yahoo');

    promise.then(
          function(payload) { 
              $scope.test = payload;
              $log.info('received data', payload);
          },
          function(errorPayload) {
              $log.error('failure loading suggestions', errorPayload);
          });    
}

angular.module('MyModule', [])
.factory('myService', function ($http, $log, $q) {
    return {
        getSuggestions: function (symbol) {            

            var deferred = $q.defer();

            $http.get('http://d.yimg.com/autoc.finance.yahoo.com/autoc', {
                cache: true,
                params: { 
                    query: symbol,
                    callback: 'YAHOO.Finance.SymbolSuggest.ssCallback'
                }
            })
            .success(function(data) {
                deferred.resolve(data);
            })
            .error(function(msg, code) {
                deferred.reject(msg);
                $log.error(msg, code);
            });

            return deferred.promise;
        }
    }
});

2 个解决方案

#1


4  

just have a look at the docs

只是看看文档

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

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

$http.get('http://autoc.finance.yahoo.com/autoc', 
  {dataType: 'jsonp', 
   jsonp: 'callback', 
   jsonpCallback: 'YAHOO.Finance.SymbolSuggest.ssCallback'}).success(function(data){ alert("yes"); });

#2


0  

Use Ajax call and you have to use promise

使用Ajax调用,你必须使用promise

And use only test not {{test()}}

并且只使用test {{test()}}

Because in your controller when you call your factory ajax function then in controller you get undefined response.

因为在你的控制器中调用你的工厂ajax函数然后在控制器中得到未定义的响应。

So use promise.

所以使用诺言。

Service:

服务:

var demoService = angular.module('demoService', [])
.service('myService',['$http', function($http) {

    this.getdata = function(entity){
        var promise = $http({
            method : 'GET',
            url : 'services/entity/add',
            data : entity,
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'YAHOO.Finance.SymbolSuggest.ssCallback',
            headers : {
                'Content-Type' : 'application/json'
            },
            cache : false
        }).then(function (response) {
            return response;
        });
        return promise;     
    };
}]);

Controller :

控制器:

var demoService = angular.module('demoService', [])
.controller('myctr',['$scope','myService',function($scope,myService){
   myService.getdata().then(function(response){
            //Success

        },function(response){

            //Error         
        });

}]);

now you can see your json in controller success

现在你可以在控制器成功中看到你的json了

#1


4  

just have a look at the docs

只是看看文档

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

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

$http.get('http://autoc.finance.yahoo.com/autoc', 
  {dataType: 'jsonp', 
   jsonp: 'callback', 
   jsonpCallback: 'YAHOO.Finance.SymbolSuggest.ssCallback'}).success(function(data){ alert("yes"); });

#2


0  

Use Ajax call and you have to use promise

使用Ajax调用,你必须使用promise

And use only test not {{test()}}

并且只使用test {{test()}}

Because in your controller when you call your factory ajax function then in controller you get undefined response.

因为在你的控制器中调用你的工厂ajax函数然后在控制器中得到未定义的响应。

So use promise.

所以使用诺言。

Service:

服务:

var demoService = angular.module('demoService', [])
.service('myService',['$http', function($http) {

    this.getdata = function(entity){
        var promise = $http({
            method : 'GET',
            url : 'services/entity/add',
            data : entity,
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'YAHOO.Finance.SymbolSuggest.ssCallback',
            headers : {
                'Content-Type' : 'application/json'
            },
            cache : false
        }).then(function (response) {
            return response;
        });
        return promise;     
    };
}]);

Controller :

控制器:

var demoService = angular.module('demoService', [])
.controller('myctr',['$scope','myService',function($scope,myService){
   myService.getdata().then(function(response){
            //Success

        },function(response){

            //Error         
        });

}]);

now you can see your json in controller success

现在你可以在控制器成功中看到你的json了