【发布时间】:2015-11-23 20:18:38
【问题描述】:
$http.get('/data.json')
.then(function(){console.log('ok'})
.catch(function(){console.log('no ok')})
服务器响应是:
200 OK
content-type: application/json
{error:'cannot get the data'}
我希望回复到.catch 而不是.then。
我知道我可以从服务器更改响应标头,但我只想在客户端这样做。
换句话说:
我如何制作 Angular $http 承诺服务,认为 200 OK 状态,在响应对象中带有“错误”键,将转到 catch 而不是调用 then功能?
【问题讨论】:
-
你试过使用'throw'吗?
-
你不能在
then处理程序中分支吗? -
'catch' 只是 'then' 函数的简写,因此 promise 显然永远不会转到 'then' 函数,并且由于 promise 已被处理,它永远不会转到 'catch'。此外,您在 then 函数中缺少响应对象
-
有点迂腐,扩展@Indrajith 的评论。 Catch 是 then(null, function(response) { alert('error catch') }) 的简写。所以它只实现了 then 函数中的第二个参数。
标签: javascript angularjs