【问题标题】:AngularJs is empty listAngularJs 是空列表
【发布时间】: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


【解决方案1】:

您在控制器中使用$location 而不是$scope 来分配视图中所需的属性。视图看不到$location中的东西

改成

function indexController($scope, index) {
    /* jshint validthis:true */
    $scope.qwets = index.query();
}

正如上面 cmets 中提到的,$resource 最初会返回一个空数组(或对象),随后将在实际请求完成时填充该数组,然后内部观察者将在它到达时更新视图

HTML ng-repeat 中的“div”也不在 div 控制器中

【讨论】:

    猜你喜欢
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2015-01-06
    相关资源
    最近更新 更多