【问题标题】:why my res.data returns array of objects ? (AngularJs)为什么我的 res.data 返回对象数组? (AngularJs)
【发布时间】:2021-11-26 06:55:07
【问题描述】:

我正在尝试使用 angularjs 使用 api 并使用 ng-repeat 重复数据,但我在访问对象数据时遇到问题。

这是我得到的反馈。

(20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} , {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

0:{名称:'bulbasaur',网址:'https://pokeapi.co/api/v2/pokemon/1/'}

1:{名称:'ivysaur',网址:'https://pokeapi.co/api/v2/pokemon/2/'}

2:{名称:'venusaur',网址:'https://pokeapi.co/api/v2/pokemon/3/'}

3:{名称:'charmander',网址:'https://pokeapi.co/api/v2/pokemon/4/'}

...还有更多

$$hashKey: "object:3" 长度:20

<script>
        angular.module('Pokedex', []).controller('myController', function ($scope, $http) {
            $scope.pokemons = []

            let getPokemons = function () {
                $http.get('https://pokeapi.co/api/v2/pokemon/?offset={qtd')
                    .then(function (res) {
                        let pokemon = res.data.results
                        console.log(pokemon)
                        $scope.pokemons.push(pokemon)
                    })
            }
            getPokemons()
        })
    </script>
<body ng-controller="myController" ng-app="myapp">
    <div>
        <ul>
            <li ng-repeat="pokemon in pokemons">
                <h2>{{ pokemon.name }}</h2>
            </li>
        </ul>
    </div>

如果我做 pokemon[0].name,我只能访问该名称。 我尝试使用地图,但无法访问数组数据,而且我对这个版本的 angular 不是很熟悉,我哪里出错了?

【问题讨论】:

  • 返回数组,因为 API 旨在这样做。但是,地图应该在这里正常工作。能否请您与map 分享您使用的代码?

标签: javascript angularjs


【解决方案1】:

您应该将 api 中的响应数组分配给 $scope.pokemons

如果您像现在一样将 api 响应推送到 $scope.pokemons 数组,您的完整响应将位于 $scope.pokemons[0] 位置下,因此您无法在模板中使用 ng-reeat 循环它。

工作小提琴

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
  $scope.pokemons = []

  let getPokemons = function () {
    $http.get('https://pokeapi.co/api/v2/pokemon/?offset={qtd')
      .then(function (res) {
        let pokemon = res.data.results
        console.log(pokemon)
        $scope.pokemons = pokemon;
      })
  }
  getPokemons()
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <div>
    <ul>
      <li ng-repeat="pokemon in pokemons">
        <h2>{{ pokemon.name }}</h2>
      </li>
    </ul>
  </div>
</div>

【讨论】:

    【解决方案2】:

    ng-repeat 中需要 ng-repeat

    请参考:

    <ul ng-repeat="pokemon in pokemons">
        <li ng-repeat="(key, value) in pokemon">
            <h2>{{ value.name }}</h2>
        </li>
    </ul>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-06
      • 1970-01-01
      • 2019-01-19
      • 2020-09-13
      • 2021-12-30
      • 2011-04-23
      • 2012-10-09
      相关资源
      最近更新 更多