AngularJS 实施 $q

AngularJS implement $q

( function() {
  angular.module('foo')

  .factory('someFac', function ($injector, $http, $q){
      var temp;
      $http.get('url').then(function(response){ //implement $q to wait for this to finish
           if(response === 1){
               temp = 1
           else{
               temp = 2
      });
     return $injector.get(temp); 
}());

我如何实现 $q 以在返回之前解决承诺?

虽然 http 做了 return 承诺,但您可以像现在这样处理结果并使用 $q 库:

( function() {
angular.module('foo')

  .factory('someFac', function ($injector, $http, $q){
    var temp;
    var deferred = $q.defer();
    $http.get('url').then(function(response){ //implement $q to wait for this to finish
       if(response === 1){
           deferred.resolve(1);
       else{
           deferred.reject(2);
  });
 return deferred.promise; 
}());

您可以拒绝或解决并通过 defer 对象传递必要的数据。

你在app.js文件中添加这段代码,你不需要从服务器端抛出异常,你只需在异常中添加代码就像

public ActionResult YourMethodName(string emailAddress)
    {
        BasicResponse Response = new BasicResponse();

        try
        {
           // do your work here
        }
        catch (Exception ex)
        {
            Response.ErrorKey = ex.Message;
            Response.ErrorCode = (int)HttpStatusCode.BadRequest;
        }

        return Json(Response, JsonRequestBehavior.AllowGet);
    }

它会自动捕获$q服务,你可以在服务器代码中添加你想要的错误代码并在开关中映射到这里

angular.module('foo').factory('responeInterceptor', ['$q', '$window', '$injector', 'NotificationService', function ($q, $window, $injector, notifyService) {
    return {
        'response': function (response) {
            // do something on success
            return response;
        },

        //in case of Error
        'responseError': function (rejection) {


            switch (rejection.status) {
                case 400:
                    notifyService.notifyError(rejection.data.errorKey);
                    break;
                case 403:
                    $window.location.href = '/Logout';
                    break;
                default:
            }
            return $q.reject(rejection);
        }
    };
}]);