Angular JS:异步工厂调用问题 [英] Angular JS: Async factory call issue
问题描述
我是 angular 的新手,我正在创建一个简单的应用程序.它在项目之间导航,通过 JSON 拉入:
I'm new to angular and I'm creating a simple app. It navigates between projects, pulled in via JSON:
http://plnkr.co/edit/FTfa1rcVaf85xTu65oSR?p=preview
我还使用了一个工厂,在那里我进行了诸如 get
或 getOne
之类的调用,以便它处理 $http
在一个地方,只有在尚未获取数据时才调用它.
I am also using a factory, where I make a call such as get
or getOne
, so that it deals with the $http
in one place, only calling it if the data hasn't already been fetched.
当您在主页上开始时,这一切正常,但是当您在单个项目页面上开始时,同时调用 get
和 getOne
,拉入重复数据.您可以通过在其自己的窗口中打开 Plunker 并转到诸如 /#/projects/1
之类的 url 来测试这一点.
This all works fine when you start on the home page, but when you start on an individual project page, both get
and getOne
are called at the same time, pulling in duplicate data. You can test this by opening the Plunker in it's own window and going to a url such as /#/projects/1
.
我知道为什么会这样,我就是不知道如何阻止它.
I know why this is happening, I just can't figure out how to stop it.
是否有一个简单的解决方法,或者我是否以完全错误的方式解决这个问题?
Is there a simple fix for this or am I going about it the completely wrong way?
感谢观看.
推荐答案
让你的函数通过 $q
返回 promise,而不是原始数据.然后你就可以用 .then()
链接它们来实现你需要的等待:
Have your functions return promises via $q
, instead of raw data. Then you'll be able to chain them with .then()
to achieve the wait you need:
get: function() {
// Create a deferred object
var deferred = $q.defer();
// Do stuff in here
// ...
// and depending on the results,
// call deferred.resolve(data) or deferred.reject(error)
// Return the promise object
return deferred.promise;
}
然后,在调用这个函数的代码中,你可以:
Then, in the code that calls this function, you can:
MyFactory.get().then(function (data) {
$scope.var = data;
}
这种模式在 Angular 中很常见,而且效果很好.
This pattern is pretty common in Angular, and works well.
更新的 plunkr:此处.我改变了你模拟服务器请求延迟的方式,以便我可以轻松地在 $http
.success() 回调中解析我的 deferred
对象代码>.
Updated plunkr: here. I switched around the way you were simulating the server request lag so that I could easily resolve my deferred
object in the .success()
callback of $http
.
这篇关于Angular JS:异步工厂调用问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!