不能访问范围变量以外的restangle请求

时间:2022-08-27 18:04:09

The rest api returns a json object on restangular get request and the response is only accessible inside the function

rest api在restangle get请求上返回一个json对象,并且响应只能在函数内部访问

 Restangular.all('getUsers').getList().then(function(response) {
    $scope.users = response;
    angular.forEach($scope.users, function(value, key) {    //This works
        console.log(key + ': ' + value);
    });
  });

  angular.forEach($scope.users, function(value, key) {    //This does not work
        console.log(key + ': ' + value);
    });

1 个解决方案

#1


3  

Read (more) about promises in angularjs.

阅读(更多)关于angularjs的承诺。

The function inside the then() is executed only after the REST request has returned a response.

只有在REST请求返回响应之后,才执行then()中的函数。

The code below that is run immediately after the request has been send, but definitely before the response has been processed.

下面的代码在请求被发送后立即运行,但肯定是在响应被处理之前。

You could do

你可以做

$scope.$watch("users", function() {
   angular.forEach($scope.users, function(value, key) {    //This does now work
           console.log(key + ': ' + value);
       });
});

#1


3  

Read (more) about promises in angularjs.

阅读(更多)关于angularjs的承诺。

The function inside the then() is executed only after the REST request has returned a response.

只有在REST请求返回响应之后,才执行then()中的函数。

The code below that is run immediately after the request has been send, but definitely before the response has been processed.

下面的代码在请求被发送后立即运行,但肯定是在响应被处理之前。

You could do

你可以做

$scope.$watch("users", function() {
   angular.forEach($scope.users, function(value, key) {    //This does now work
           console.log(key + ': ' + value);
       });
});