AngularJS $promise then() data undefined

后端 未结 4 665
伪装坚强ぢ
伪装坚强ぢ 2021-01-05 10:24

I am trying to get data assigned to a $scope variable. Inside my $promise.then() function it is displaying correctly but outside the function it shows as undefined. The foll

相关标签:
4条回答
  • 2021-01-05 11:06

    The function passed to .then() will be called after the data has been fetched from the backend. The other console.log() (the one outside of .then()) will be called immediately after the request has been made, and not after it has been completed, thus the tasks is undefined.

    Consider the timing (of course times are only an example):

    // 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); 
    
    0 讨论(0)
  • 2021-01-05 11:10

    This code will help you to fetch data and resolve with promise, please note fetch data will only work after then call...

    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));
          })
        }
    
    0 讨论(0)
  • 2021-01-05 11:18
    $scope.test.$promise.then(function(data) {
    
    if(data){    
    $scope.tasks = data.tasks;
    }
    
    console.log($scope.tasks);
    });
    

    try this

    0 讨论(0)
  • 2021-01-05 11:26

    It's a promise so it sets $scope.task after it returns. Until that return occurs $scope.task is undefined, which is what your second console.log is showing . At some later time the promise is resolved (completes) and $scope.task has a value, which is what your first console.log shows.

    0 讨论(0)
提交回复
热议问题