【问题标题】:Querying Web API with AngularJS使用 AngularJS 查询 Web API
【发布时间】:2018-08-08 09:49:49
【问题描述】:

我一直关注this tutorial 并拥有以下控制器:

(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")));  

模块:

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

和html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Music App</title>
<script src="../../Scripts/angular.js"></script>
<script src="../../Scripts/jquery-1.10.2.js"></script>
<link href="../../Content/Site.css" rel="stylesheet" />
<link href="../../Content/bootstrap.css" rel="stylesheet"/>
<script src="../../Scripts/bootstrap.js"></script>
<script src="../Scripts/theMusic.js"></script>
<script src="../Scripts/MusicListController.js"></script>
</head>
<body>
<div ng-app="theMusic">
    <div ng-controller="MusicListController">
        <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>
    </div>
</div>
</body>
</html>

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

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

有人可以帮忙吗?

谢谢

【问题讨论】:

  • 首先,查看开发工具 ( F12 ),在网络选项卡下查看您的 http 调用返回什么。

标签: angularjs html asp.net-web-api


【解决方案1】:

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

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

$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 响应中提取)作为参数传递给回调函数。

【讨论】:

  • $scope.musics = data; 更改为$scope.musics = data.data; 做到了。谢谢!
【解决方案2】:

你应该做 data.data 来收集响应:

var MusicListController = function ($scope, $http) {
    $http.get("/api/Musics").then(function (data) {
        $scope.musics = data.data;
    },function (response){}
    );
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多