简体   繁体   English

如何在Angular中处理JSON响应

[英]How to deal with JSON response in Angular

I have the following controller: 我有以下控制器:

function EntryCtrl($scope, Restangular){
 console.log("*** EntryCtrl");
 $scope.roles= Restangular.all("roles").getList();
 console.log("*** EntryCtrl: " +  JSON.stringify($scope.roles));
}

The console output is: 控制台输出为:

*** EntryCtrl: {"restangularCollection":true} 

When I use a rest browser plugin to make the same rest call, I get: 当我使用rest浏览器插件进行相同的rest调用时,我得到:

[
 {
     "name": "dev"
 }
]

I cannot figure out how to get Angular to process the response same as the rest browser plugin. 我无法弄清楚如何使Angular与其余浏览器插件一样处理响应。 My ultimate goal is to just get the role name, "dev", in Angular. 我的最终目标是在Angular中获得角色名称“ dev”。 On an Angular page, I want to use "ng-show" on a link using the role name, like this: 在Angular页面上,我想在使用角色名称的链接上使用“ ng-show”,如下所示:

<a href="" ng-show="roles.contains('')>Foo</a>

Try with 试试看

$scope.roles= Restangular.all("roles").getList().$object;

from the doc 文档

Does a GET to /accounts Returns an empty array by default. GET到/ accounts是否默认返回一个空数组。 Once a value is returned from the server that array is filled with those values. 从服务器返回值后,该数组将被这些值填充。 So you can use this in your template 因此您可以在模板中使用它

$scope.accounts = Restangular.all('accounts').getList().$object;

According to the doc: 根据文档:

Restangular uses promises. 矩形使用承诺。 Instead of doing the "magic" filling of objects like $resource 而不是像$ resource这样的对象进行“魔术”填充

So to get the response from the server, you have to use .then callback like so: 因此,要从服务器获取响应,必须使用.then回调,如下所示:

Restangular.all("roles").getList().then(function(response){
    $scope.roles = response;
});

And in your template: 在您的模板中:

<li ng-repeat="role in roles">{{role.name}}</li>

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

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