从 Angular AJAX 调用返回数据的模式 [英] Pattern for returning data from Angular AJAX calls
问题描述
看看工厂返回的这个方法:
Take a look at this method returned in a factory:
fetchEmployeeList: function() {
var q = $q.defer();
$http.get('/Employee/')
.success(q.resolve)
.error(ajaxErrorHandler.handleError);
return q.promise;
}
这段代码的作者说这是我们应该用于从 HTTP 端点返回数据的模型.基本上,任何时候我们需要来自服务的数据,我们都应该使用这种模式.作者的印象是,这比返回 $http.get() 的返回值更受欢迎.
The author of this code says that this is the model we should use for returning data from HTTP endpoints. Basically, any time we need data from a service, we should use this pattern. The author is under the impression that this is preferred over returning $http.get()'s return value instead.
不过,我不明白这段代码的意义.我认为 $http.get() 确实会返回一个承诺.
I don't understand the point of this code, though. I thought $http.get() does return a promise.
有人可以解释一下这个示例代码片段在做什么,或者他们认为作者可能想要做什么吗?
Can someone explain what this example snippet is doing or what they think the author might be trying to do?
推荐答案
那是延期的 反模式,它实际上在不需要时扭曲了承诺.
That's the deferred anti-pattern, which practically warps a promise when not needed.
在您的情况下,返回 q.promise 似乎是一种滥用,因为 HTTP 对象本身可以返回一个承诺.
in your case returning a q.promise seems like an abuse since the HTTP object can return a promise itself.
我会将代码重构为以下内容:
I'd refactor the code to the following:
fetchEmployeeList: function() {
return $http.get('/Employee/');
}
你可以看看这个博文也可提供更多参考,
you can take a look to this blog post for more reference as well,
不要害怕与提出这种方法的人进行讨论.
don't be afraid to open a discussion with whoever is suggesting that approach.
这篇关于从 Angular AJAX 调用返回数据的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!