【问题标题】:angularjs how to catch http response data that sent by browserangularjs如何捕获浏览器发送的http响应数据
【发布时间】:2016-11-25 20:45:23
【问题描述】:

作为标题,我想捕捉浏览器发送的 Http 响应。
假设重定向到“http://domain/api/something”,实际上是对“http://domain/api/something”的 GET 请求,它返回 JSON 数据。
如何使用 AngularJs 在首次加载时获取该数据?

【问题讨论】:

  • 请更详细地描述您要完成的工作,并尝试这样做。
  • 假设用户在浏览器上输入我的页面“domain/api/something”然后我的服务器返回一个 JSON 数据/一个 Html 页面左右。如果是 Html 页面,浏览器将呈现它。问题是,我怎样才能在不发送另一个请求的情况下获得文本/HTML 格式的 Html 页面。

标签: angularjs http


【解决方案1】:

你应该修改你的代码如下

app.service('feedbackService', function ($http) {
   this.getFeedbackPaged = function () {
      return $http.get('http://domain/api/something');
   };
});

app.controller('feedbackController', function ($scope, feedbackService, $filter) {
  // Constructor for this controller
  init();

  function init() {
      feedbackService.getFeedbackPaged().then(function(data){
          $scope.feedbackItems=data;
      });
  }
});

【讨论】:

  • 这样,我会发送另一个请求,而不是捕获浏览器已经发送的响应,不是吗?
  • 请提供更多描述性。一旦你加载了 init();它将调用 http GET 方法并且响应将存储在 $scope.feedbackItems 中。谢谢
【解决方案2】:

如下使用$http服务。

$http.get(
  'http://domain/api/something'
).then(function successCallback(response) {
  $scope.data = JSON.parse(response.data);
}, function errorCallback(response) {
  // error handler
});

参考:https://docs.angularjs.org/api/ng/service/$http

【讨论】:

    猜你喜欢
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    相关资源
    最近更新 更多