在角正确使用承诺 [英] Correct use of Promises in Angular

查看:141
本文介绍了在角正确使用承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让我的头缠着承诺在AngularJS的概念。

在正确的轨道上以下code?而可能有人解释 PlateCheckService.checkPlate 方法和为什么如果我不回的承诺? 返回$ http.post()。然后为什么对象的内部收益与的消息 alertClass 不起作用?我认为这是一个链接/内承诺?

  ///<参考路径=angular.js/>
(函数(){
使用严格VAR应用= angular.module('CS');app.service('PlateCheckService',['$ HTTP',函数($ HTTP){
    返回{
        checkPlate:功能(plateNumber){
            返回$ http.post('PlateCheck /指数',{
                plateNumber:plateNumber
            })。然后(功能(响应){
                返回{
                    消息:response.data.VehicleAtl ===空? 干净:热,
                    alertClass:response.data.VehicleAtl ===空? 警报的成功':'警报的危险
                }
            });
        }
    }
}]);app.controller('PlateCheckCtrl',['$范围,PlateCheckService',函数($范围,PlateCheckService){
    VAR plateCheck = {
        车牌号码: '',
        信息: '',
        alertClass:'',
        checkPlate:功能(plateNumber){
            VAR _this =这一点;            PlateCheckService.checkPlate(plateNumber)。然后(功能(响应){
                _this.message = response.message;
                _this.alertClass = response.alertClass;
            });
        }
    };    $ scope.plateCheck = plateCheck;
}]);}());


解决方案

是的,这是因为链的承诺。请记住,一个呼叫然后将它围住调用的函数返回前的承诺。

所以,您的通话位置: PlateCheckService.checkPlate(plateNumber)将希望返回一个链接承诺。然而,你的服务的然后封闭功能没有返回的承诺。因此,将无法有一个然后函数链一旦解决了。

您可以用下面的伪code想象这样的:

  $ http.get(URL)
    。然后(功能(响应){
        返回aPromise;
    })
    。然后(功能(aPromiseResponse){
        返回bPromise;
    })
    。然后(功能(bPromiseResponse){
        返回cPromise;
    })
    。然后(功能(cPromiseResponse){
        //当范围可
        $ scope.bindToMe = cPromiseResponse.value;
    });

如果你想在服务功能添加到一个承诺链,然后包裹承诺函数需要返回一个承诺为好。

我发现要做到这一点,最简单的方法是用 $ q.when $ q.when 将包装对象中承诺,如果该对象不是一个承诺。如果对象是已经可以(像你的情况),那么 $ q.when 将即刻解决。对于文档 $ q.when 这里

所以,你应该能够得到您的code。通过在服务中使用这个工作:

 收益$ q.when({
          消息:response.data.VehicleAtl ===空? 干净:热,
          alertClass:response.data.VehicleAtl ===空? 警报的成功':'警报的危险
       });

I am trying to get my head wrapped around the concept of Promises in AngularJS.

Is the following code on the right track? And could someone explain the PlateCheckService.checkPlate method and why if I don't return the promise? return $http.post().then why the inner return of the object with the message and alertClass does not work? I think it is a chained/inner promise?

/// <reference path="angular.js" />
(function () {
"use strict"

var app = angular.module('cs');

app.service('PlateCheckService', ['$http', function ($http) {
    return {
        checkPlate: function (plateNumber) {
            return $http.post('PlateCheck/Index', {
                plateNumber: plateNumber
            }).then(function (response) {
                return {
                    message: response.data.VehicleAtl === null ? 'Clean' : 'Hot',
                    alertClass: response.data.VehicleAtl === null ? 'alert-success' : 'alert-danger'
                }
            });
        }
    }
}]);

app.controller('PlateCheckCtrl', ['$scope', 'PlateCheckService', function ($scope, PlateCheckService) {
    var plateCheck = {
        plateNumber: '',
        message: '',
        alertClass: '',
        checkPlate: function (plateNumber) {
            var _this = this;

            PlateCheckService.checkPlate(plateNumber).then(function (response) {
                _this.message = response.message;
                _this.alertClass = response.alertClass;
            });
        }
    };

    $scope.plateCheck = plateCheck;
}]);

}());

解决方案

Yes, it is because of chained promises. Remember that a call to then will return a promise before the function it encloses is called.

So, your call here: PlateCheckService.checkPlate(plateNumber) will expect to return a chained promise. However, your service's then enclosed function is not returning a promise. Therefore, it will fail to have a then function to chain once it is resolved.

You can visualize this with the following psuedo code:

$http.get('url')
    .then(function(response) {
        return aPromise;
    })
    .then(function(aPromiseResponse) {
        return bPromise;
    })
    .then(function(bPromiseResponse) {
        return cPromise;
    })
    .then(function(cPromiseResponse) {
        // when scope is available
        $scope.bindToMe = cPromiseResponse.value;
    });

If you want to add functionality to a promise chain in a service, then the wrapped promise function needs to return a promise as well.

The easiest way I have found to do this is with $q.when. $q.when will wrap the object in a promise if the object is not a promise. If an object is already available (like in your case), then $q.when will instantly resolve. Documentation for $q.when is here.

So, you should be able to get your code to work by using this in the service:

return $q.when({
          message: response.data.VehicleAtl === null ? 'Clean' : 'Hot',
          alertClass: response.data.VehicleAtl === null ? 'alert-success' : 'alert-danger'
       });

这篇关于在角正确使用承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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