这里
我附上了服务调用的示例程序。我第一次遇到问题,无法正确获取值。
第一次调用:
<小时/>第二次或多次调用:
<小时/>我可以知道问题出在哪里吗?并帮我修复。 为什么首先执行 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/