我正在多个页面中使用来自 RESTful 服务的一些数据。
所以我为此使用角度工厂。因此,我需要从服务器获取一次数据,并且每次我都使用该定义的服务获取数据。就像全局变量一样。这是示例:
var myApp = angular.module('myservices', []);
myApp.factory('myService', function($http) {
$http({method:"GET", url:"/my/url"}).success(function(result){
return result;
});
});
在我的控制器中,我将此服务用作:
function myFunction($scope, myService) {
$scope.data = myService;
console.log("data.name"+$scope.data.name);
}
按照我的要求,它对我来说工作得很好。
但这里的问题是,当我重新加载网页时,服务将再次被调用并请求服务器。如果在依赖于“定义的服务”的其他函数执行之间,它会给出诸如“某物”未定义之类的错误。所以我想在我的脚本中等待,直到服务加载。我怎样才能做到这一点?无论如何,AngularJS 中有这样做吗?
当您不知道异步操作何时完成时,您应该使用 Promise。承诺“代表一项尚未完成但预计将在未来完成的操作”。 (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)
一个示例实现如下:
myApp.factory('myService', function($http) {
var getData = function() {
// Angular $http() and then() both return promises themselves
return $http({method:"GET", url:"/my/url"}).then(function(result){
// What we return here is the data that will be accessible
// to us after the promise resolves
return result.data;
});
};
return { getData: getData };
});
function myFunction($scope, myService) {
var myDataPromise = myService.getData();
myDataPromise.then(function(result) {
// this is only run after getData() resolves
$scope.data = result;
console.log("data.name"+$scope.data.name);
});
}
编辑:关于 Sujoy 的评论
我需要做什么才能使 myFuction() 调用在 .then() 函数完成执行之前不会返回。
function myFunction($scope, myService) {
var myDataPromise = myService.getData();
myDataPromise.then(function(result) {
$scope.data = result;
console.log("data.name"+$scope.data.name);
});
console.log("This will get printed before data.name inside then. And I don't want that.");
}
好吧,我们假设对 getData() 的调用需要 10 秒才能完成。如果该函数在那段时间没有返回任何内容,它实际上会变成正常的同步代码,并会挂起浏览器直到完成。
不过,随着承诺立即返回,浏览器可以同时继续处理其他代码。一旦 Promise 解决/失败,就会触发 then() 调用。因此,这种方式更有意义,即使它可能会使代码流程变得更加复杂(毕竟复杂性是异步/并行编程的常见问题!)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)