我用.net Core和AngularJs + webApi制作简单的程序 我的Api代码如下 运行后没有Js错误,问题是factory return Nothing。 当我在 $location.qwets = index.query(); 设置断点时我的“qwets”是空的,“qwets”的长度是0。 每次页面刷新时 get 方法都有效,但结果什么也没有。
I changed the code now I have results in 'qwets' but index is still empty
谢谢
// 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>
最佳答案
您在 Controller 中使用 $location
而不是 $scope
来分配 View 中所需的属性。该 View 看不到 $location
更改为
function indexController($scope, index) {
/* jshint validthis:true */
$scope.qwets = index.query();
}
正如上面评论中提到的,$resource 最初将返回一个空数组(或对象),随后将在实际请求完成时填充该数组,然后内部观察程序将在到达时更新 View
Also bad end "div" in HTML ng-repeat not in div controller
关于javascript - AngularJs 是空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40702216/