繁体   English   中英

服务返回的值未在angularjs的控制器变量中更新

[英]Value returned by service not update in controller's variable in angularjs

function getList() {

        SubCategoryService.getAllList().then(function (response) {
            $scope.subCategoryList = response.data;
            $scope.subCategoryDetailsList = [];

            var subCategoryDetails = [];



            for(var i=0; i < $scope.subCategoryList.length; i++) {

                var subCategoryListData = $scope.subCategoryList[i];

                var subcategory = {
                    'id' : subCategoryListData.id,
                    'category' : '',
                    'name' : subCategoryListData.name,
                    'created_on' : subCategoryListData.created_on,
                    'modified_on' :  subCategoryListData.modified_on,
                    'is_deleted' : subCategoryListData.is_deleted,
                    'is_active' : subCategoryListData.is_active,
                    'image_name' : subCategoryListData.image_name,
                    'image_path' : subCategoryListData.image_path
                }

                CategoryService.getCategoryById(subCategoryListData.category_id).then(function(response1) {
                    console.log(response1.data);
                    subcategory.category = response1.data;

                }, function(error) {
                    swal("Error", error.data, "error");
                })

                subCategoryDetails.push(subcategory);
            }

            console.log(JSON.stringify(subCategoryDetails));

        }, function (error) {
            swal("Error", "Something went wrong", "error");
        });
    }

CategoryService:

  this.getCategoryById = function(id) {
            return $http({
                url: globalUrl.baseurl + 'category/getCategoryById/' + id,
                method: 'GET'
            })
        }

在上面的代码中,我试图从CategoryService服务中获取数据,并且它成功返回CategoryService.getCategoryById函数中的数据。 现在,我试图通过服务将返回值分配给控制器中存在的subcategory.category。 但是我的问题是它没有更新subcategory.category中的值。

我的猜测是:

您可以在执行API call之前(由于js回调)在array中推送新的变量,可以尝试执行以下操作:

CategoryService.getCategoryById(subCategoryListData.category_id)
.then(function(response1) {
    console.log(response1.data);
    subcategory.category = response1.data;

    // PUSHING AFTER API RETURNS THE VALUE
    subCategoryDetails.push(subcategory);

}, function(error) {
    swal("Error", error.data, "error");
})

// subCategoryDetails.push(subcategory);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM