Angularjs $ HTTP等待回应 [英] Angularjs $http wait for response

查看:585
本文介绍了Angularjs $ HTTP等待回应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手的JavaScript / angularjs。我想说明一个引导酥料饼当鼠标悬停上的一些元素进行。

I am a newbie to javascript/angularjs. I want to show a bootstrap popover when mouseover is done on some elements.

我创建了一个指令

(function(angular, app) {
  app.directive('popOver',["$window","$http",function($window,$http){
    return function(scope,elem,attrs){
      elem.on('mouseover',function(){
        console.log('mouseover');
        var data = scope.$apply(attrs.popOver);
        console.log('in directive again');
        console.log(data);
      });
    };
  }]);
})(angular, app);

该指令的值是一个函数

the value of the directive is a function

<跨度类=ASDF,弹出了=getVCard(ID)>名称< / SPAN>

函数电子名片(ID)在我angularjs控制器被限定。它检查数据是否已经存在在localStorage的,如果present,返回数据。否则不执行一个$ HTTP GET请求,并在localStorage的存储数据。

the function vcard(id) is defined in my angularjs controller. It checks if the data is already there in localstorage and if present, returns the data. otherwise it does a $http get request and stores the data in localstorage.

$scope.getVCard = function(id){

  var vcardKey = vcardKeyPrefix+id;

  var vCardFromLS = localStorageService.get(vCardKey);
  if(vCardFromLS){
    return localStorageService.get(vCardKey);
  }

  $http.get(app.common.vcardUrl(id)).
    success(function(data){
      localStorageService.set(vCardKey,data);
    }).
    error(function(error){
      F1.common.error(data,function(){});
    });

    return localStorageService.get(vCardKey);
};

由于$ HTTP回报的承诺,我在我的指令得到undefined值。我怎样才能确保功能 getVCard 同步返回?

我在Google上搜寻后,读了多项成果。但所建议的想法是使用回调。但我不知道回调将如何使这个同步的。任何帮助是AP preciated。

I read a number of results after googling. But the suggested idea is to use callbacks. But i am not sure how callbacks will make this synchronous. Any help is appreciated.

更新1 (响应美孚L的评论)
我正打算使用在多个地方相同指令。 popovers用于vCard和产品信息等。这将是不同的唯一事情是参数弹出了指令。这样,该指令将理会只是显示弹出。从哪里获得的数据将在传递的指令一个单独的函数

UPDATE 1 (in response to Foo L's comment) i was planning to use the same directive in multiple places. popovers for vcards and product information and so on. The only thing that will differ is the argument to the pop-over directive. That way the directive will bother about just displaying the popup. Where to get the data will be in a separate function that is passed to the directive

推荐答案

您不能强迫 $ http.get()进入同步。由于 $ http.get()不可避免地异步的,你只能返回一个值,而不是值本身的承诺。

You can't force $http.get() into synchronism. Since $http.get() is unavoidably asynchronous, you can only return a promise of a value not the value itself.

因为你需要做到这一点时, $ http.get()被调用时,还必须其他情况下返回一个承诺 - 当 vCardFromLS 成功从localStorage的retreived。这确保了对象返回到 $ scope.getVCard的任何呼叫()有一个。然后()方法,也就是说,它是一个承诺,无论 $ http.get()被称为与否。

And because you need to do this when $http.get() is called, you must also return a promise under the other condition - when vCardFromLS is successfully retreived from localstorage. This ensures that the object returned to any call of $scope.getVCard() has a .then() method, ie it is a promise, regardless of whether $http.get() was called or not.

所以,code应该是这样的:

So the code should be something like this :

$scope.getVCard = function(id) {
    var vcardKey = vcardKeyPrefix + id;
    var vCardFromLS = localStorageService.get(vCardKey);
    var dfrd = $q.defer();
    if(vCardFromLS) {
        dfrd.resolve(localStorageService.get(vCardKey));
    }
    else {
        $http.get(app.common.vcardUrl(id)).success(function(data) {
            localStorageService.add(vCardKey, data);//.add() rather than .set() ?
            dfrd.resolve(data);
        }).error(function(error) {
            F1.common.error(data, function() {
                dfrd.reject('$http.get(app.common.vcardUrl(id)) failed');
            });
        });
    }
    return dfrd.promise;
};

现在,你需要确保对 $ scope.getVCard响应()是适当的处理,例如:

Now you need to ensure that the response to $scope.getVCard() is handled appropriately, eg :

$scope.getVCard(id).then(function(data) {
    //success - do whatever is required with data
}, function(reason) {
    //failure - log and/or display `reason` as an error message
})

编辑:

我的......您必须同时返回其他条件下的诺言......是言过其实。

My "... you must also return a promise under the other condition ..." is an overstatement.

我应该说,......你的可以,使事情变得简单,其他情况下返回一个承诺......

I should have said, "... you can, to make things simple, return a promise under the other condition ...".

另一种可能性是,这取决于是否返回一个承诺或其他类型的对象/值的分支。然而,这是混乱的,通常会导致code一些重复。

Another possibility is to branch depending on whether a Promise or another type of object/value was returned. However, this is messy and will typically lead to some duplication of code.

这篇关于Angularjs $ HTTP等待回应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆