角JS:异步调用工厂问题工厂、问题、JS

2023-09-13 03:34:47 作者:兄弟視命°

我新的角度和我创建一个简单的应用程序。它导航项目之间,通过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=$p$ PVIEW

我还使用了工厂,在那里我打个电话,如 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和去一个URL,例如 /#/测试这个项目/ 1

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 的承诺。然后,你就可以连锁它们与。然后()来达到你所需要的等待:

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;
}

然后,在code调用此功能,您可以:

Then, in the code that calls this function, you can:

MyFactory.get().then(function (data) {
    $scope.var = data;
}

本模式是角pretty常见,而且效果很好。

This pattern is pretty common in Angular, and works well.

更新plunkr: 这里。我换你身边是模拟服务器请求滞后,这样我可以很容易解决的方式我延迟对象的 .success()的回调 $ HTTP

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.