关于html:使用AngularJS查询Web API

Querying Web API with AngularJS

我一直在关注本教程,并具有以下控制器:

1
2
3
4
5
6
7
8
9
(function (app) {
var MusicListController = function ($scope, $http) {
    $http.get("/api/Musics").then(function (data) {
        $scope.musics = data;
    },function (response){}
    );
};
app.controller("MusicListController", MusicListController);
}(angular.module("theMusic")));

模块:

1
2
3
(function () {
var app = angular.module('theMusic', []);
}());

和html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
Music App
<script src="../../Scripts/angular.js">
<script src="../../Scripts/jquery-1.10.2.js">
<link href="../../Content/Site.css" rel="stylesheet" />
<link href="../../Content/bootstrap.css" rel="stylesheet"/>
<script src="../../Scripts/bootstrap.js">
<script src="../Scripts/theMusic.js">
<script src="../Scripts/MusicListController.js">
</head>
<body>

   
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Singers</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="music in musics">
                    <td>{{music.Title}}</td>
                    <td>{{music.Singers}}</td>
                </tr>
            </tbody>
        </table>
   

</body>
</html>

它应该显示API请求的结果,但是当前显示的只是一个空表。 我怀疑我的问题出在我的$http.get.then函数的某个地方,因为本教程使用了似乎已弃用的$http.get.success,并且我查找了执行该问题的新方法。

如果我在调试时转到(localhost)/ api / musics,它会返回其中包含数据的XML文件。

有人可以帮忙吗?

谢谢


当您使用$http.get("...").then()时,您在回调中作为参数传递的对象(then内的函数)所得到的不是data本身,而是整个HTTP响应。 因此,您必须访问响应内的data

在您的情况下,假设Web API响应如下:{"musics": [{"author":"Jon Doe","title":"abc"}]} ...您需要这样做:

1
2
3
4
$http.get("/api/Musics").then(function (response) {
    $scope.musics = response.data; // <-- here we are getting the object `data` which is inside the whole `response`
},function (response){}
);

这与已弃用的$http.get.success不同,后者实际上将data(从HTTP响应中提取)作为回调函数的参数。


您应该执行data.data来收集响应:

1
2
3
4
5
6
var MusicListController = function ($scope, $http) {
    $http.get("/api/Musics").then(function (data) {
        $scope.musics = data.data;
    },function (response){}
    );
};