AngularJS:控制器之间的数据服务
我有一个带有主控制器和嵌套控制器的页面,用于显示有关产品的详细信息。我想使用angular中的服务调用服务器,检索数据对象并保存该数据对象。主控制器将调用服务获取数据,详细信息控制器需要知道数据已更新,然后访问数据。我的服务如下所示:AngularJS:控制器之间的数据服务,angularjs,angularjs-service,Angularjs,Angularjs Service,我有一个带有主控制器和嵌套控制器的页面,用于显示有关产品的详细信息。我想使用angular中的服务调用服务器,检索数据对象并保存该数据对象。主控制器将调用服务获取数据,详细信息控制器需要知道数据已更新,然后访问数据。我的服务如下所示: .service("productService", function ($http, $q) { var product = {}; //interface that is returned return ({ fetch
.service("productService", function ($http, $q) {
var product = {};
//interface that is returned
return ({
fetchProduct: fetchProduct,
clearProduct: clearProduct,
product: product
});
function fetchProduct(ID) {
var request = $http({
method: "get",
url: "/online/productdata.ashx?itemID=" + ID,
params: {
action: "get"
}
});
return (request.then(handleSuccess, handleError));
};
function clearProduct() {
product = {};
};
// Transform the error response, unwrapping the application dta from
// the API response payload.
function handleError(response) {
// The API response from the server should be returned in a
// nomralized format. However, if the request was not handled by the
// server (or what not handles properly - ex. server error), then we
// may have to normalize it on our end, as best we can.
if (
!angular.isObject(response.data) ||
!response.data.message
) {
return ($q.reject("An unknown error occurred."));
}
// Otherwise, use expected error message.
return ($q.reject(response.data.message));
};
// I attempt to transform the successful response and unwrap the application data
// from the API response payload.
function handleSuccess(response) {
product = response.data;
console.log("Found Data: " + angular.toJson(response.data))
return (response.data);
};
})
在我的主控制器中,我将scope对象设置为服务,如下所示:
$scope.SelectedProduct=productService
当用户单击按钮以显示产品时,将通过$scope句柄调用该产品:
$scope.SelectedProduct.fetchProduct(ID)
详细信息控制器对$scope.SelectedProduct具有相同的分配。我不熟悉使用服务,但我理解的是angular将绑定到服务对象,而对属性产品的更改将触发绑定到任何更新。事实上,我确实在fetch操作之后看到了数据。在服务中,我在返回的数据上有一个console.log,它显示了正确的数据。但是,产品属性未得到更新。有人能告诉我我做错了什么吗?获取数据后,两个控制器都无权访问该数据。我知道我得到的是一个承诺,但即使在超时检查之后,数据也永远不存在 尝试使用工厂而不是服务
我会将此答案标记为正确答案,因为这部分是我所做的修复工作。真正的问题更加微妙。当数据调用返回数据时,问题是该技术没有将数据分配给服务属性的属性,而是有效地更改了指向该属性的指针,因此它丢失了。我确实将其更改为factory,但我也将传入数据附加到product对象的属性。这样做效果很好。谢谢你的回复。这是我第一次没有得到一个快速的解决方案,我怀疑这是由于我对问题的陈述。JS有它的怪癖。