【发布时间】:2015-01-26 21:31:07
【问题描述】:
我正在使用 Angular 1.3 我已将代码更改为使用 Controller as,而不是使用 $scope。
我有一个网址:
http://localhost:3640/api/v1/topics
得到以下 json:
[
{
topicId: 17,
title: "This is another BRAND SPANKIN new topic",
body: "This is a message in the body of another topic ftw!",
created: "2014-11-27T05:37:49.993",
replies = null
},
{
topicId: 18,
title: "This is another BRAND new topic",
body: "This is a message in the body of a topic wow!",
created: "2014-11-27T05:37:49.993",
replies = null
}
]
我还有一个名为 index-home.js 的页面
var app = angular.module("myApp", []);
app.controller("homeIndexController", ["$http", function ($http) {
var msg = this;
msg.dataCount = 0;
msg.replies = [];
$http.get("/api/v1/topics?includeReplies=true")
.success(function(data) {
//Success
msg.replies = data;
})
.error(function() {
//Error
alert('error/failed');
});
}]);
在我的页面上,我使用以下绑定:
<div id="ngController" ng-controller="homeIndexController as hic">
...
<h3>Message count: {{hic.dataCount}}</h3>
...
<div class="message row" data-ng-repeat="i in hic.data">
<div class="title">{{i.title}}</div>
<div class="date">{{i.created}}</div>
<div class="contents">{{i.body}}</div>
</div>
我知道 $http 中的 url 可以正常工作,因为我在浏览器和 fiddler 中自己尝试了它,它返回了 json。但是当我在我的角度应用程序中使用它时,我得到了 .error 结果(这是一个警告说失败。
我尝试删除 http://localhost:3640 并在我这样做时只使用 /api/v1/topics,我不再得到错误结果。我知道我的控制器正在工作并绑定到页面,因为我得到了 dataCount 的 0。
我在$http 方法中做错了什么?我的语法错了吗?
【问题讨论】:
-
转到 chrome 的开发者工具,网络选项卡并查看请求是否从浏览器触发。如果是,请检查请求详细信息和响应流。
-
@MadhavanKumar 是的,调用已完成,json 在响应中返回。
-
感谢@MadhavanKumar 的帮助,你让我走上了一条坦率地说我在调试中不习惯的道路。检查 F12 工具以查看数据响应等。但问题实际上非常愚蠢。我要求
ng-repeat="i in hic.data"而不是ng-repeat="i in hic.replies"显然是一个新手错误,但很难抓住,因为一个指向另一个。因此,如果不仔细查看代码,我的所作所为几乎是有道理的。这通常是 JavaScript 中的问题。我们没有编译器或类型来帮助我们,说嘿,白痴,你叫错了。
标签: json angularjs asp.net-mvc-5 http-get