【发布时间】:2017-04-03 18:55:09
【问题描述】:
我用 .net Core 和 AngularJs + webApi 制作了简单的程序 我的 Api 代码如下 运行后没有Js错误问题是工厂返回什么都没有。 当我在 $location.qwets = index.query(); 上设置断点时我的“qwets”为空,“qwets”的长度为 0。 每次页面刷新时get方法都有效,但结果什么都没有。
我更改了代码,现在我得到了 'qwets' 的结果,但索引仍然是空的
谢谢
// GET: api/values
[HttpGet]
public IEnumerable<ApplicationUser> Get()
{
return new List<ApplicationUser> {
new ApplicationUser {Id="test", Email="test1@test.com" },
new ApplicationUser {Id="tst2",Email="test2@test.com" }
};
}
app.js 文件是
(function () {
'use strict';
angular.module('saniehhaApp', [
// Angular modules
//'ngRoute'
// Custom modules
"indexService"
// 3rd Party Modules
]);
})();
(function () {
'use strict';
angular
.module('saniehhaApp')
.controller('indexController', indexController);
indexController.$inject = ['$location', 'index'];
function indexController($location, index) {
index.query()
.$promise.then(function (result) {
$scope.qwets = result;
}
})();
(function () {
'use strict';
var indexService = angular.module('indexService', ['ngResource']);
indexService.factory('index', ['$resource',
function ($resource) {
return $resource('/api/index/', {}, {
query:
{
method: 'GET',
params: {},
isArray: true
}
});
}]);
})();
还有我的 index.html 文件
<!DOCTYPE html>
<html ng-app="saniehhaApp">
<head>
<meta charset="utf-8" />
<title>SampleTest</title>
<script src="vendor/angular.min.js"></script>
<script src="vendor/angular-resource.min.js"></script>
<script src="vendor/angular-route.min.js"></script>
<script src="scripts/app.js"></script>
</head>
<body ng-cloak>
<div ng-controller="indexController"></div>
<h2>list of users</h2>
<ul>
<li ng-repeat="qwet in qwets">
<p> "{{qwet.Id}}" - {{qwet.Email}}</p>
</li>
</ul>
</body>
</html>
【问题讨论】:
-
您能否检查开发者栏中的网络选项卡,看看 API 调用是否返回了预期的数据?可以在问题中粘贴响应数据吗?
-
您所描述的是默认的
$resource行为。该请求是异步的,因此$resource最初返回一个空数组,然后在请求完成时填充该数组。除非您需要在数据到达时立即在控制器中执行某些操作,否则这应该不是问题……视图中的观察者仍会更新诸如 ng-repeat 之类的内容 -
问题是使用
$location而不是$scope -
@sabithpocker 是的,我检查了网络的 api 返回值。
-
@charlietfl 没有帮助。谢谢
标签: javascript angularjs asp.net-web-api asp.net-core