javascript - 在 Angular 服务调用中,第一次问题没有获得值(value)?

标签 javascript jquery angularjs

Here Demo Link

这里我附上了服务调用的示例程序。我第一次遇到问题,无法正确获取值。

第一次调用:

<小时/>

enter image description here

第二次或多次调用:

<小时/>

enter image description here

我可以知道问题出在哪里吗?并帮我修复。 为什么首先执行 count,然后执行 datalength?

最佳答案

$http.get 默认情况下调用异步。我们必须使用 Promise 来使其同步。使用此更新的代码请参阅 Plunker :

var app = angular.module('myApp', []);

app.controller('myCtrl', ['$scope', '$location', '$filter', 'sampleService', '$http', function ($scope, $location, $filter, sampleService, $http) {
    $scope.getCount = function () {
        sampleService.getFile().then(function (data) {
            var dt = data.PRTGetSlotsBySessionResult;
            var count = $filter('filter')(dt, { "N": null });
            alert(JSON.stringify(count.length));
        });
    }
}]);

app.factory('sampleService', ['$http', '$filter', '$q', function ($http, $filter, $q) {

    return {
        object: '',
        makeRequest: function (url) {
            // Create the deffered object
            var deferred = $q.defer();
            $http.get(url).then(function (resp) {
                deferred.resolve(resp.data);
            });

            return deferred.promise;
        },
        getFile: function () {
            if (!this.object) {
                this.object = this.makeRequest("file.json");
            }
            // Return the myObject stored on the service
            return this.object;
        }
    };
}]);

关于javascript - 在 Angular 服务调用中,第一次问题没有获得值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40486510/

相关文章:

javascript - 从 iframe 中获取 iframe 的 URL 参数

jquery - 我怎样才能随着值(value)的增加而减少随机百分比

javascript - Angular isState - 如何在 ng-if 内进行比较?

javascript - 如何渲染路线 View ?

javascript - 将 cURL 从 Swiftype API 转换为 Parse.httpRequest

javascript - 使用 jquery 中的值设置单选按钮

javascript - Angular Directive(指令) : whats the difference between scope in controller vs scope in link function?

java - 如何从同一模型中的不同表中检索对象列表?

javascript - 使用 JSON 解析/解析 js 对象时,返回方法中的函数范围会丢失

javascript - 事件监听器问题