【问题标题】:Angular $http timeout returning undefinedAngular $http超时返回未定义
【发布时间】:2015-05-21 20:16:25
【问题描述】:

我只是在使用 Angular 的 $http 模块测试超时功能,但是它一直返回 undefined 作为响应

这样设置也没问题,但如果我在$http 调用中添加.error(function) 而不是.then(function),它会在尝试从未定义对象中获取数据字段时抛出错误

var timeout = $q.defer();

var config = {
        url: 'http://192.168.1.65:3000',
        timeout: timeout.promise,
        method: 'POST'
    };

    $http(config).then(function(res) {
        // This is always undefined when timeout occurs
        console.log(res);
    });

    $timeout(function() {
        console.log('resolving the promise to abort the http call. This works fine');
        timeout.resolve();
    }, 1000);

任何想法我做错了什么?

【问题讨论】:

  • 您没有将值传递给您的 resolve 调用。
  • 我不认为这是问题所在,我只是尝试进行健全性检查,并没有改变任何东西......根据这个其他答案,这应该就是你所需要的
  • 您是要超时还是取消请求?我不得不在我的工作地点使用类似的东西,我不认为timeout 接受承诺。如果您要取消请求,请将 cancellationToken 设置为承诺。你还用了什么其他答案?
  • @gfunk,当请求超时时,它是一个被拒绝的承诺 - 所以你需要.catch
  • 哦,对不起...这是答案stackoverflow.com/a/21916315/3325262

标签: angularjs


【解决方案1】:

$http 超时时,它会返回一个拒绝的承诺,您可以使用.catch 处理:

$http(config)
  .then(function(response){
  })
  .catch(function(error){
     // will fire when timed out
  })

Demo

题外话:直接使用$timeout生成的promise其实更简单,不需要$q.defer

var timeout = $timeout(angular.noop, 1000);
$http.get(url, {timeout: timeout})
     .then(...)
     .catch(...)

编辑:

如果有拦截器,则超时将导致responseError,如果定义,该拦截器本质上“处理”错误,因此它不再成为被拒绝的承诺,结果被路由到.then -如果您没有从responseError 函数返回任何内容,则传递给.then 处理程序的数据是undefined。如果您想保留拒绝,您可以这样做:

// inside http inteceptor
responseError: function(rejection){

  if (rejection.status === 0){ // if timeout
    return $q.reject({reason: "timeout"});
  }
  // ...
}

【讨论】:

  • 如果这是真的,那么为什么他的console.log 打印未定义? :s
  • @DanPantry,如果按照他在问题中所说的那样实施,那么它就不会到达那里。也许其他东西正在打印"undefined"
  • @NewDev 你是对的,代码中有一个拦截器捕获错误然后返回 undefined
  • @gfunk,这是一个非常重要的数据点:)
猜你喜欢
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
  • 2019-09-26
  • 1970-01-01
  • 2019-10-19
  • 2017-01-08
  • 2018-07-21
  • 2019-07-28
相关资源
最近更新 更多