簡體   English   中英

無法訪問$ scope中的對象

[英]Can't access object in $scope

我在服務中有以下代碼:

      return {
          getReport: function(data){
            var request = $resource(getResourcePath('report'));
            return request.get(data, function(response) {
                return response;
            }).$promise;
          }
      }

這段代碼在我的控制器中:

    ReportService.getReport(customStruct).then(function(response){
        console.log("respo", response);
        $scope.reportData = {response}
    });

    console.log("$scope1", $scope)
    console.log("$scope2", $scope.reportData)

但是當我嘗試訪問$scope.reportData ,我得到的是undefined 這是$scope1$scope2輸出的屏幕截圖:

在此處輸入圖片說明

為什么我不能訪問$scope.reportData對象? 請幫助並提前致謝。

看起來您正在處理經典的“我的數據在哪里”異步問題。 Angular和JavaScript從http調用返回承諾 Promise有點像Angular交給您的盒子,並說“當數據返回時,我將其放入此盒子中”。 問題是,如果您嘗試訪問框中的數據,則該數據將不存在(包括console.log)。

如果必須在加載視圖之前獲取數據,請考慮使用$ routeProvider(ng-route)或$ stateProvider(ui-router)的解析功能。 例如:

$stateProvider.state('app.reports', {
    url: 'reports/reports.html',
    ...
    resolve : {
       reportData : function(ReportService) {
            return ReportService.getReport(customStruct);
       }
    }
});

然后在您的控制器中,將reportData指定為依賴關系:

.controller('someController', ['$scope',
                                'reportData',
                                function($scope, reportData){
    $scope.reportData = reportData;
}]);

這迫使Angular在加載視圖之前等待reportData解析。 但是,還有一個陰暗的一面:如果響應花費了幾毫秒以上的時間才能返回,則UI可能會感覺無響應

需要指出的最后幾點。 這行:

    $scope.reportData = {response}

我不確定通過將響應包裝在一個對象中來完成什么。 最后這一行:

        return request.get(data, function(response) {
            return response;
        })

您可能要考慮返回response.data而不是response(其中包含標頭和其他如果成功則可能不需要的其他東西)。

祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM