【问题标题】:AngularJS,how to get data from an API and display itAngularJS,如何从 API 获取数据并显示它
【发布时间】:2020-06-28 22:32:02
【问题描述】:

我正在尝试学习 angularJS。我正在尝试从以 JSON 格式提供艺术家数据的 API 获取数据。我要做的是获取在文本栏中输入的名称,然后将接收到的信息显示为 JSON。 API 接受的格式是 url/艺术家名 + 应用程序 ID 作为请求,其中艺术家名是输入。我尝试使用 API 的人给了我一个有效的应用程序代码,该代码存储在 var id 中。 到目前为止,我已经编写了以下代码,任何帮助将不胜感激。谢谢!

    var myApp = angular.module('myApp', []);
    myApp.controller('UserCtrl', function($scope,$http){
        $scope.user = null;
        var id = "my secret id comes here";

        var name = $scope.searchText;
        $scope.getByID = function() {

            $http.get("https://rest.bandsintown.com/artists/" + name + id)
                    $scope.user = response;
                    console.log(response)
                }

              });

接下来,html代码是:

<body ng-app="myApp">
    <div ng-controller="UserCtrl">
        Search : <input type="text" placeholder="Search Employees" ng-model="searchText"/> <br/><br/>
        <button ng-click="UserCtrl.getByID()">Submit</button>
</body>

谢谢,对不起,如果这是一个新手问题,我确实是新手!

【问题讨论】:

    标签: html json angularjs


    【解决方案1】:

    response 没有在任何地方声明,所以看起来您只需要正确处理 $http.get 响应。以下应该有效:

     var myApp = angular.module('myApp', []);
     myApp.controller('UserCtrl', function($scope, $http) {
       $scope.user = null;
    
       var id = "my secret id comes here";
       var name = $scope.searchText;
    
       $scope.getByID = function() {
         // $http.get returns a promise, you'll need to set the variables there.
         $http.get("https://rest.bandsintown.com/artists/" + name + id)
           .then(response => {
             $scope.user = response;
             console.log(response)
           })
       }
     });
    
    

    【讨论】:

      猜你喜欢
      • 2023-01-22
      • 2021-03-12
      • 1970-01-01
      • 2018-11-10
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 2020-11-22
      • 2022-06-13
      相关资源
      最近更新 更多