2

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;
        }
    }
});
Community
  • 1
  • 1
Matthias
  • 5,574
  • 8
  • 61
  • 121
  • possible duplicate of [from jquery $.ajax to angular $http](http://stackoverflow.com/questions/12131659/from-jquery-ajax-to-angular-http) – Grundy Jun 25 '15 at 11:03
  • `url: 'http://autoc.finance.yahoo.com/autoc',` – Grundy Jun 25 '15 at 11:04
  • in doc: https://docs.angularjs.org/api/ng/service/$http#jsonp – Grundy Jun 25 '15 at 11:05
  • Yeah, but my problem is what to do with this parameter: jsonpCallback How to put that into the http.jsonp call? – Matthias Jun 25 '15 at 11:10
  • Yeah, solved it. The http call works and the result is ok. Just need to insert a promise and handle the return value accordingly. Thanks all for your help. – Matthias Jun 25 '15 at 17:58

2 Answers2

4

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"); });
messerbill
  • 5,499
  • 1
  • 27
  • 38
  • Thanks for the hint. I updated [the JsFiddle](https://jsfiddle.net/Nagilo/g77s0y6s/1/) but still does not work :( – Matthias Jun 25 '15 at 11:27
  • Just run the JsFiddle and you will see the error on the JavaScript console. It's somewhat about mixed HTTP and HTTPS call and a syntax error which I can not find. – Matthias Jun 25 '15 at 11:33
  • PS: I'm using Chrome on MacOS. – Matthias Jun 25 '15 at 11:41
  • this is because you try to load scripts from http to a https page. do you have loaded you angular and jquery to your harddisc locally? – messerbill Jun 25 '15 at 11:52
  • 1
    Nope, I only use JsFiddle. You have to use this URL: http://d.yimg.com/autoc.finance.yahoo.com/autoc And in [this JsFiddle](http://jsfiddle.net/S8yyD/18/) it works fine. hmmm – Matthias Jun 25 '15 at 12:30
  • hm at first you should not develop with jsfiddle. But if you do, use AngularJS as library and not jquery and dont include external scripts. this should work, but like i said, better develop on your local system. and dont forget to inject the $http correctly - https://docs.angularjs.org/guide/di – messerbill Jun 25 '15 at 13:35
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/81544/discussion-between-matthias-and-messerbill). – Matthias Jun 25 '15 at 14:53
  • now how you will print your response in html using controller – Keval Bhatt Jun 26 '15 at 04:36
0

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

Keval Bhatt
  • 6,224
  • 2
  • 24
  • 40
  • Good idea, but I wanted to use pure Angular.JS for learning reasons. But you are right, I need to use at least a promise. – Matthias Jun 25 '15 at 11:28
  • k if you need any help let me know – Keval Bhatt Jun 25 '15 at 11:39
  • Thanks. I'm still trying to fix the fiddle with the help of the other answer. – Matthias Jun 25 '15 at 11:40
  • @Matthias https://jsfiddle.net/kevalbhatt18/84e02j4t/2/ i created this but error wiil be show 404 for your URL – Keval Bhatt Jun 25 '15 at 11:50
  • The URL was wrong: Use this one http://d.yimg.com/autoc.finance.yahoo.com/autoc But then you get the HTTPS error. And you also need to add the query parameter. Just use any name like 'yahoo' – Matthias Jun 25 '15 at 12:30