【问题标题】:In angular, how can I catch the moment when an ajax request is successfully sent?在 Angular 中,如何捕捉成功发送 ajax 请求的时刻?
【发布时间】:2014-07-16 18:38:08
【问题描述】:

使用 angular $resource,我想在请求成功发送到 restful 后端时触发回调函数。 (后端可能需要很长时间,我只想知道它是否收到了我发送的数据。)

目前我发现的唯一东西是resource.action.$promise['finally'](callback);

我也想知道何时无法发送请求。 (例如连接问题)

谢谢!

【问题讨论】:

    标签: angularjs angular-resource


    【解决方案1】:

    这里是 DRY 方法:

    构建一个拦截每个 HTTP 请求的服务(like the one defined in the official documentation):

       $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
        return {
          // optional method
          'request': function(config) {
            // do something on success
            return config;
          },
    
          // optional method
         'requestError': function(rejection) {
            // do something on error
            if (canRecover(rejection)) {
              return responseOrNewPromise
            }
            return $q.reject(rejection);
          },
    
    
    
          // optional method
          'response': function(response) {
            // do something on success
            return response;
          },
    
          // optional method
         'responseError': function(rejection) {
            // do something on error
            if (canRecover(rejection)) {
              return responseOrNewPromise
            }
            return $q.reject(rejection);
          }
        };
      });
    

    只需将您的代码放入所需的挂钩中即可。例如,如果请求失败,您可以绘制一个错误模式对话框。

    最后,将其注册到您的应用程序中:

    app.config(['$httpProvider', function($httpProvider) {
            // Add the interceptor to the $httpProvider to intercept http calls
            $httpProvider.interceptors.push('myHttpInterceptor');
    
        }]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 2015-09-27
      • 2015-03-30
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多