2

我正在使用 Angular 和 $http 请求从服务器获取数据。它是同一服务器目录中的模拟数据,但它会在 20 秒内返回响应。这是很长的路。该请求在应用程序启动时执行。我尝试使用 jQuery $.ajax 执行相同的查询,它在 10 毫秒内运行。但我想摆脱 jQuery。为什么 AngularJs $http 花了这么长时间?

我正在使用 Ifeanyi Isitor 的Lazy Loading In AngularJS示例如何将 require.js 与 angular 一起使用。加载我的第一个视图的控制器指向执行查询的服务。在 chrome 开发工具网络跟踪中,我发现 10 毫秒获取文件所需的时间更少。但是在执行查询之前使用console.time设置它并在成功时结束它承诺它会记录大约20000毫秒。可能是因为延迟加载吗?但为什么 jQuery 工作得很快?这是我的服务代码

define(['appModule'], function(app) {
  app.lazy.factory('daoService', ['$http', function($http) {
    var ...
    ...
    getChanges = function(tableName, modifiedSince, callback) {
        console.log('data access time starts');
        console.time('data access time');
        // this works in 20000 ms
        $http.post(tablesUrl[tableName]).success(function(data) {
                console.log("The server returned " + data.length + " changes);
                console.timeEnd('data access time');
                callback(data);
            }).error(function(data){
                console.log(data);
            });

        /* this works in about 10 ms
        $.ajax({
            url: tablesUrl[tableName],
            dataType:"json",
            success:function (data) {
                console.log("The server returned " + data.length + " changes );
                console.timeEnd('data access time');
                callback(data);
            },
            error: function(model, response) {
                console.log(response);
            }
        });*/
    },
4

1 回答 1

1

我找到了答案。我是因为必须调用 Angular 中的某些东西才能执行。为此,我们需要使用 $apply。这是代码:

define(['appModule'], function(app) {
    app.lazy.factory('daoService', ['$http', '$rootScope', function($http, $rootScope) {
    var ...
    ...
    getChanges = function(tableName, modifiedSince, callback) {
        $rootScope.$apply(function(){
                $http.post(tablesUrl[tableName], params).success(function(data) {
                    callback(data);
                }).error(function(data){
                    console.log(data);
                    phoneGapApp.showAlert(data.message);
                });   
            });
    },

更多关于 $apply 在Jim Hoskins 的帖子中

于 2013-08-30T10:22:18.350 回答