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;
        }
    }
});
5
  • possible duplicate of from jquery $.ajax to angular $http Commented Jun 25, 2015 at 11:03
  • url: 'http://autoc.finance.yahoo.com/autoc', Commented Jun 25, 2015 at 11:04
  • in doc: docs.angularjs.org/api/ng/service/$http#jsonp Commented Jun 25, 2015 at 11:05
  • Yeah, but my problem is what to do with this parameter: jsonpCallback How to put that into the http.jsonp call? Commented Jun 25, 2015 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. Commented Jun 25, 2015 at 17:58

2 Answers 2

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"); });
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for the hint. I updated the JsFiddle but still does not work :(
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.
PS: I'm using Chrome on MacOS.
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?
Nope, I only use JsFiddle. You have to use this URL: d.yimg.com/autoc.finance.yahoo.com/autoc And in this JsFiddle it works fine. hmmm
|
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

5 Comments

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.
k if you need any help let me know
Thanks. I'm still trying to fix the fiddle with the help of the other answer.
@Matthias jsfiddle.net/kevalbhatt18/84e02j4t/2 i created this but error wiil be show 404 for your URL
The URL was wrong: Use this one 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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.