在我的案例中,如何传递http请求结果

How to pass a http request result in my case?

本文关键字:何传递 http 请求 结果 我的 案例      更新时间:2023-09-26

我正在尝试将http请求结果发送给我的子控制器。

我有类似的东西

<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的请求结果,但我不确定如何将其传递给我的子控制器。有人能帮我吗?

谢谢!

潜在方法:

1) 将myFactory也注入到子控制器中。

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

$scope.$parent.productDetail

3) 如果想要从HTML 访问

$parent.productDetail

上面假设您希望访问该值,该值与子作用域上的潜在版本特别分离(现有代码没有显示这一点)。

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