javascript - 拦截 $resource 和 $http 响应 Angular

标签 javascript angularjs

我有一个 json 响应:

{
  "success": false,
  "error": "Server says no.",
  "data": []
}

包裹在$resource中,如下所示:

$resource("path-to-file.json", null, {
  query: {
    method: "GET",
    isArray: false,
    responseType: "json",
    interceptor: {
      response: function (response) {
        if (!response.data.success) {
          // stop propagation of events/promises and trigger error
        }
        // do something else with response.data
        return response;
      }
    }
  }
});

如果"success": false我想触发$http的错误函数。

我想这样做:

$scope.myVar = MyService.query(); // MyService returns $resource

在 Controller 中。无论我尝试做什么,响应都会传递到 $scope.myVar

最佳答案

值得记住的是:

The ngResource module provides interaction support with RESTful services 1

当他们说“RESTful 服务”时,他们的意思是他们正在对您的端点的行为方式做出一些假设。这些假设之一是成功或错误状态将由 HTTP 状态代码编码。

听起来您正在尝试与不符合此模式的服务进行交互(即您可能会遇到返回200: OK的失败请求)。如果是这种情况,您可能最好直接使用 $http ,因为它更通用:

The $http service is a core Angular service that facilitates communication with the remote HTTP servers 2

由于 $resource 实际上只是 $http 的包装,我们可以通过查看 the source 来相当轻松地确认行为。 (为清楚起见进行了编辑):

var promise = $http(httpConfig).then(function(response) {
  var data = response.data,
      promise = value.$promise;

  // snip

  value.$resolved = true;

  response.resource = value;

  return response;
}, function(response) {
  value.$resolved = true;

  (error||noop)(response);

  return $q.reject(response);
});

promise = promise.then(
    function(response) {
      var value = responseInterceptor(response);
      (success||noop)(value, response.headers);
      return value;
    },
    responseErrorInterceptor);

请记住,then() 按顺序接受成功和错误回调。您可以看到您的拦截器将在成功时被调用,以及主要的成功回调(如果有)。

看起来您在 responseInterceptor 内无法执行任何操作来导致执行错误回调。

我认为你的选择是:

  • 修改您的服务器,使其按照 $resource 期望的方式运行
  • 滚动构建在 $http 之上的您自己的 $resource 版本,按照 this answer 中的建议按照您希望的方式工作。 .

关于javascript - 拦截 $resource 和 $http 响应 Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20519225/

相关文章:

javascript - jsPlumb beforeDrop 和 ngToast 消息未立即显示

java - 使用 struts 加载页面时,JSP 下拉列表默认选择第一个选项

javascript - slideDown 强制显示 :block

javascript - JS 正则表达式 : How to replace lines of text within a specific area?

angularjs - 设备在线时如何将离线数据库与 Firebase 同步?

javascript - 注册后自动登录

javascript - ISO 日期字符串的 Alfresco、Tomcat6 和 javascript 处理

javascript - 匹配最高选项卡的高度 - 设置幻灯片高度

angularjs - 什么是基于 DOM 的模板?

javascript - 一段时间后隐藏带有angularjs表单验证的错误标签