簡體   English   中英

AngularJS $promise then() 數據未定義

[英]AngularJS $promise then() data undefined

我正在嘗試將數據分配給 $scope 變量。 在我的 $promise.then() 函數內,它顯示正確,但在函數外它顯示為未定義。 以下是我的控制器代碼:

angular.module('testSiteApp').controller('TestController', function ($scope, Tests) { 

$scope.test = Tests.get({id: 1});

$scope.test.$promise.then(function(data) {
    $scope.tasks = data.tasks;
    console.log($scope.tasks);
});

console.log($scope.tasks); 

});

then() 函數內的結果:

[Object, Object, Object, Object]

then() 函數之外的結果:

undefined

我正在使用的“測試”服務工廠如下:

angular.module('testSiteApp').factory('Tests', function($resource) {

return $resource('/api/test/:id', {id: '@id'}, { 'update': { method: 'PUT' } } );

});

即使我對我的資源使用查詢方法而不是 get 並將 isArray 設置為 true ,我仍然會遇到同樣的問題。 由於某種原因,數據沒有綁定到 then 函數內的我的范圍。

如果這是一個重復的問題,我很抱歉,但我到處尋找,只發現與 $promise 函數相關的未定義問題,這在這種情況下不是問題。

預先感謝您的支持。

從后端獲取數據后,將調用傳遞給.then()的函數。 另一個console.log() (在.then()之外的那個)將在請求發出后立即調用,而不是在請求完成后調用,因此tasks是未定義的。

考慮時間(當然時間只是一個例子):

// time = 0.000 sec. You make a request to the backend
$scope.test = Tests.get({id: 1});

$scope.test.$promise.then(function(data) {
    // time = 1.000 sec. Request is completed. 
    // data is available, so you assign it to $scope.tasks
    $scope.tasks = data.tasks;
    console.log($scope.tasks);
});

// time = 0.000 sec (!!!) This has been called NOT AFTER
// the callback, but rather immediately after the Tests.get()
// So the data is not available here yet.
console.log($scope.tasks); 

這是一個承諾,所以它返回設置 $scope.task 。 在返回之前 $scope.task 是未定義的,這就是您的第二個 console.log 顯示的內容。 稍后,promise 得到解決(完成)並且 $scope.task 有一個值,這就是您的第一個 console.log 顯示的值。

$scope.test.$promise.then(function(data) {

if(data){    
$scope.tasks = data.tasks;
}

console.log($scope.tasks);
});

嘗試這個

此代碼將幫助您獲取數據並使用 promise 進行解析,請注意獲取數據僅在調用...

getData(){
      const promise = this.httpClient.get(this.PHP_API_SERVER+'/api/books').toPromise();  
      promise.then((data)=>{
        console.log("Resolved: " + JSON.stringify(data));
        return JSON.stringify(data);
      }, (error)=>{
        console.log("Rejected " + JSON.stringify(error));
      })
    }

暫無
暫無

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

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