gpt4 book ai didi

javascript - 在我的情况下如何传递http请求结果?

转载 作者:行者123 更新时间:2023-12-03 11:33:28 24 4
gpt4 key购买 nike

我正在尝试将 http 请求结果发送到我的子 Controller 。

我有类似的东西

<div ng-controller = "parentCtrl">
<button ng-click="callApi()">click me</button>

<div ng-controller = "childCtrl">
<div>{{productDetail}}</div>
</div>
</div>

angular.module('App').controller('parentCtrl', ['$scope','myFactory',
function($scope, myFactory) {
$scope.callApi = function() {
myFactory.request(id)
.then(function(data) {
$scope.productDetail = data
//do something in parent controller here....
})

}
}
]);

angular.module('App').controller('childCtrl', ['$scope',
function($scope) {
//I am not sure how to get the productDetail data here since it's a http request call.
}
]);



angular.module('App').factory('myFactory', function($http) {
var service = {};

service.request = function(id) {
return createProduct(id)
.then(function(obj) {
productID = obj.data.id;
return setProductDetail(productID)
})
.then(getDetail)
.then(function(productDetail) {
return productDetail.data
})
}
var createProduct = function(id) {
return $http.post('/api/product/create', id)
}

var setProductDetail = function(id) {
return $http.post('/api/product/setDetail', id)
}

var getDetail = function() {
return $http.get('/api/product/getDetail')
}

return service;
});

我能够获取我的parentCtrl的请求结果,但我不知道如何将它传递给我的子 Controller 。谁能帮我解决一下吗?

谢谢!

最佳答案

潜在的方法:

1) 将 myFactory 也注入(inject)到子 Controller 中。

2) 直接从 childCtrl 中访问父作用域:

$scope.$parent.productDetail

3)如果想从HTML访问

$parent.productDetail

上面假设您想​​要访问与子作用域上的潜在版本明确分开的值(现有代码没有显示这一点)。

如果它是一个子作用域,并且子作用域(或中间的作用域)上没有任何内容被命名为productDetail,并且您没有在具有该名称的子作用域中设置原始值,那么您应该能够看到直接通过原型(prototype)继承获取值(但是列出的三种情况中的任何一种都可能强制需要通过父级进行引用)。

关于javascript - 在我的情况下如何传递http请求结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26636603/

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