Angular JS: Async factory call issue

一世执手 提交于 2019-12-21 05:41:11

问题


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

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.

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?

Thanks for taking a look.


回答1:


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

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

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.



来源:https://stackoverflow.com/questions/28222395/angular-js-async-factory-call-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!