gpt4 book ai didi

javascript - AngularJS:解析 $http 时 $routeProvider 返回响应 obj 而不是我的 obj

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:18:47 24 4
gpt4 key购买 nike

我正在尝试解决几个 ajax 调用,以便我的 Controller 需要的数据在它(以及它提供的指令)执行之前可用。执行顺序是有效的,但是,注入(inject)到我的 Controller 中的结果不是返回我创建的对象,而是 $http 的响应对象:

{
config: { … },
data: { … },
headers: { … },
status: 200
}

我的代码基本上是这样的:

app.config([
'$routeProvider', function($routeProvider)
{
$routeProvider
.when('/path', {
…,
"resolve": {
"data": [
'$http',
function($http)
{
return $http
.get('/api/data')
.success(function(data,status) { return data.rows[0]; })
.error(function(data,status) { return false; });
}
]
}
});
}
]);

我傻了吗? $http 成功的返回值不应该实际上是 $http 返回的值吗?

我也试过


"resolve": {
"data": [
'$http',
function($http)
{
var response;
$http
.get('/api/data')
.success(function(data,status) { response = data.rows[0]; })
.error(function(data,status) { response = false; });
return response;
}
]
}

但是注入(inject)到我的 Controller 中的 data 对象是未定义的(我猜是因为 $http 是异步的并且 resolve 没有被 $http 阻塞——所以它返回了在 $http 准备好之前)。

附言$http 的同步性应该在其选项对象中定义!!

解决方案

app.config([
'$routeProvider', function($routeProvider)
{
$routeProvider
.when('/path', {
…,
"resolve": {
"data": [
'$http',
function($http)
{
return $http
.get('/api/data')
.then(
function success(response) { return response.data.rows[0]; },
function error(reason) { return false; }
);
}
]
}
});
}
]);

感谢Ajay beniwal's pointerMark Rajcok's pointer .

附言then() 记录在 $q's page 上.

最佳答案

$http @returns {HttpPromise} Returns a {@link ng.$q promise} object with the standard then method and two http specific methods: success and error. The then method takes two arguments a success and an error callback which will be called with a response object. The success and error methods take a single argument - a function that will be called when the request succeeds or fails respectively. The arguments passed into these functions are destructured representation of the response object passed into the then method. The response object has these properties:

关于javascript - AngularJS:解析 $http 时 $routeProvider 返回响应 obj 而不是我的 obj,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17706419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com