问题描述:

hmmm, i am stuck on this for a while, hopefully i can get some hints from you guys.

i put some sample code here to illustrate the issue:

http://jsfiddle.net/HB7LU/18216/

so basically, i am expecting console.log('out put data for member ' + number); get executed right after mySvc.get() rest call finishes every time i click on the member item.

$q.all([

mySvc.get({id: number})

]).then(function() {

console.log('out put data for member ' + number);

});

but it is not the case, it only works as expected the first time you click on it. second time you click on it, the opposite happens.

XHR finished loading: GET "http://fiddle.jshell.net/HB7LU/18216/show/test?id=1"

(index):53 loading data - rest call finished

(index):68 out put data for member 1 <- this is correct

(index):68 out put data for member 2 <- this is wrong, should wait till rest call finishes

XHR finished loading: GET "http://fiddle.jshell.net/HB7LU/18216/show/test?id=2

(index):53 loading data - rest call finished

ps: i tested it in chrome. havent tested it in other browsers

please let me know how i can fix it. thanks!

网友答案:

You are returning the same deferred each time instead of creating a new one, if you moved the creation of the deferred inside the get call or just returned the promise from the $http call it works fine

myService.get = function(requestParams) {
    var deffered = $q.defer();

http://jsfiddle.net/jc04arnn/

网友答案:

You need to create a new deferred each time they call .get(). See the corrected code. Because you can only resolve a deferred once, your resolving it multiple times has no event. It only resolves it the first time. After that, any time it returns that promise, it will immediately fire the .then, cause the deferred is already resolved.

myService.get = function(){
    var deffered = $q.defer();

http://jsfiddle.net/8qLrnz5o/

网友答案:

Other solution is return the promise that $http creates (first put the callback and then return the promise) :

myService.get = function(requestParams) {
    var call = $http({
        method: 'GET',
        url: TEST_DATA_URLS,
        params: requestParams
    });

    call.success(function (msg) {
      console.log('loading data - rest call finished');
    });

    return call;
};

when you call mySvs.get you have the same promise:

mySvc
     .get({id: number})
     .then(function() {
            console.log('out put data for member ' + number);
      });

Here is the fiddle: http://jsfiddle.net/tmbs0b1L/

相关阅读:
Top