简体   繁体   中英

how to convert AJAX $http call to Angular.JS

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?

That's the AJAX function (details see this posting and this 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.

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

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.

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

just have a look at the docs

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

Use Ajax call and you have to use promise

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

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

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

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