【发布时间】:2017-10-02 15:53:55
【问题描述】:
我是 AngularJS 的初学者,所以我尝试学习这个框架。 为了训练,我使用带有星球大战数据的 REST API (https://swapi.co/)。 我有一个问题:我无法在控制台日志中显示对象的值。
查看我的 Angular JS 代码:
var pokeApp = angular.module('pokedex', ['ngResource']);
pokeApp.config(['$resourceProvider', function($resourceProvider) {
$resourceProvider.defaults.stripTrailingSlashes = false;
}]);
pokeApp.controller('PokeController', function ($scope,$log, People) {
$scope.people = null;
$scope.getPeople = function(idPeople) {
$myPeople = People.get({id:idPeople});
$log.log($myPeople.name); // result in console : undefined
$scope.people = $myPeople;
$log.log($scope.people.name); // result in console : undefined
};
});
pokeApp.service('People', function($resource)
{
$jsonPeople = $resource('https://swapi.co/api/people/:id', {id:'@id'});
return $jsonPeople;
});
看看我的 HTML 代码:
<body ng-app="pokedex">
<div class="container" ng-controller="PokeController">
<h1>Star Wars Engine</h1>
<div>
<input ng-model="idPeople"/>
<button ng-click="getPeople(idPeople)">Search</button>
</div>
<br />
<div>
<table border="1" class="tableSW">
<tr>
<th>Nom</th>
<th>Sexe</th>
<th>Taille</th>
<th>Poids</th>
<th>Date de naissance</th>
<th>Couleur de peau</th>
</tr>
<tr>
<td>{{ people.name }}</td>
<td>{{ people.gender }}</td>
<td>{{ people.height }}</td>
<td>{{ people.mass }}</td>
<td>{{ people.birth_year }}</td>
<td>{{ people.skin_color }}</td>
</tr>
</table>
</div>
</div>
<!-- Dependencies -->
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/angular.min.js"></script>
<script src="js/angular-resource.min.js"></script>
<script src="js/pokedex.js"></script>
<style>
.tableSW td{
width: 150px;
}
.tableSW th{
width: 150px;
}
</style>
</body>
当我尝试在控制台中显示来自 API 的对象的值时,它包含“未定义”。
我不明白为什么,你能解释一下吗? 我指定视图中信息的显示效果很好。
非常感谢。
西蒙。
【问题讨论】:
-
如果您只记录 $log.log($myPeople); ?
-
是的,它适用于 $log.log($myPeople)... 我可以在控制台中看到对象的所有信息。
-
粘贴对象以指导您如何访问它们的属性。
-
{ "name": "Luke Skywalker", "height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair", “eye_color”:“blue”,“birth_year”:“19BBY”,“gender”:“male”,“homeworld”:“swapi.co/api/planets/1”,“species”:[“swapi.co/api/species/1”],“vehicles”: [“swapi.co/api/vehicles/14”、“swapi.co/api/vehicles/30”]、“已创建”:“2014-12-09T13:50:51.644000Z”、“已编辑”:“2014-12-20T21:17:56.891000Z”、“url ": "swapi.co/api/people/1" }
-
AngularJS 中服务的 $ 前缀旨在表明它是一个内置的服务或函数。不建议在您自己的服务、变量或函数上使用 $ 作为前缀。
标签: javascript angularjs console