我能够获取数据
 $http.jsonp("http://url/GetAll?callback=JSON_CALLBACK").
            success(function(data, status, headers, config) {
                console.log(JSON.stringify(data));
                $scope.eventSource = JSON.stringify(data);
            }).
            error(function(data, status, headers, config) {
                alert("ERROR: Could not get data.");
            });
我知道我也可以使用回调方法来获取这样的数据:
$.ajax({
        url: "http://url/GetAll",
        type: 'GET',
        dataType: 'jsonp',            
        jsonp: 'callback',
        jsonpCallback: 'myCallback'
    });
    myCallback = function (data) {
        alert(data);
        //$scope.eventSource = JSON.stringify(data);
    }
不幸的是,我需要它作为工厂或服务,并将在模块内调用。所以我尝试这样做,但它不起作用:
app.factory('calendarFactory', function ($http) {
return {
    query: function () {            
        var promise = $http.jsonp("http://url/GetAll?callback=JSON_CALLBACK").
            success(function (data, status) {
                //console.log(JSON.stringify(data));
                //myData = JSON.stringify(data);
                return JSON.stringify(data);
            }).
            error(function (data, status, headers, config) {
                alert("ERROR: Could not get data.");
            });
        return promise;
    }
}
});
控制台打印数据..但是当我尝试将其添加到范围变量时,它不起作用..
 $scope.eventSource = calendarFactory.query();
脚本引用都很好,因为它适用于虚拟数据。请不要说需要回调方法。看看我的第二个脚本。那有一个回调方法。我需要第三个脚本才能工作。肯定有问题,因为我没有在第四个脚本中获取数据。
更多更新:
我将控制器更改为:
 $scope.eventSource = [];
calendarFactory.query().success(function (data) {
        //myVar = JSON.stringify(data);
        console.log(JSON.stringify(data));
        $scope.eventSource = JSON.stringify(data);
});
console.log($scope.eventSource);
现在虽然这更有希望,但问题是日志首先显示 [] 然后显示数据。这意味着工厂调用发生得很晚。改变坚持为时已晚。我尝试使用$scope.$watch('eventSource', function () { same factory call}但这也不起作用。
现在,我真的很想得到这个工作。我什至可以考虑一个可以解决问题的自定义 JQuery 函数。
更多更新.. 所以我现在尝试使用承诺..
app.service('calendarFactory', function ($http, $q) {
return {
    query: function () {
        var deferred = $q.defer();
        $http({ method: "jsonp", url: URL })
            .success(function (data, status, headers, config) {
                deferred.resolve(data);
                //console.log(JSON.stringify(data));
            }).error(function (data, status, headers, config) {
                deferred.reject(data);
            });            
        return deferred.promise;
    }
}
});
$scope.eventSource = calendarFactory.query();
$scope.eventSource.then(function (items) {
    $scope.eventSource = JSON.stringify(items);
    //console.log(JSON.stringify(items));
}, function (status) {
    console.log(status);
});
但它仍然没有更新页面。
有人可以展示发出 JSONp 请求的角度服务的工作示例吗?