我试图使用$ resource从ASP.NET webApi获取数据,但它无法正常工作

时间:2017-04-07 09:03:36

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

You can see the errors in the image

我是webapi的新手,也是有角度的,无法找到合适的解决方案,请帮帮我,如果可以,请向我推荐一些很好的资源来了解这个主题。

productResource.js文件:

(function () {
    "use strict";

    angular.module('Random')
    .factory('productResource', function ($resource) {
        return $resource("http://localhost:60208/");
    });
});

T.js文件

var app = angular.module("JobsApp", []);
app.controller("JobController", function($scope,$http,productResource)
{
    $scope.Jobs = productResource.query();
});

Index.cshtml文件:

<div ng-app="JobsApp">
    <div ng-controller="JobController">
        <table class="table">
            <tr>
                <th>Job Id</th>
                <th>Description</th>
                <th>Minimum</th>
                <th>Maximum</th>
            </tr>
            <tr ng-repeat="j in Jobs">
                <td>{{j.job_id}}</td>
                <td>{{j.job_desc}}</td>
                <td>{{j.min_lvl}}</td>
                <td>{{j.max_lvl}}</td>
            </tr>
        </table>
    </div>
</div>

2 个答案:

答案 0 :(得分:0)

您需要向模块注入ngResource才能使其正常运行。像

(function () {
    "use strict";    
    angular.module('Random',['ngResource'])
    .factory('productResource', function ($resource) {
        return $resource("http://localhost:60208/");
    });
});

<强>更新

您的网址似乎也不正确。您需要在后端创建一个WebAPI controller类来进行通信,它应该像/User/jobs一样RESTful。

此外,请确保您已在应用中添加angular-resource.js

答案 1 :(得分:0)

请参阅此http://fdietz.github.io/recipes-with-angular-js/consuming-external-services/consuming-restful-apis.html

制作如下代码..

&#13;
&#13;
var app = angular.module("JobsApp",["ngResource"]);
app.controller("JobController",['$scope','productResource', function($scope,  productResource){
   productResource.query(function(value) {
		$scope.Jobs=value;
    //console.log(value);
	});
}]);

app.factory('productResource', function ($resource) {
return $resource('http://jsonplaceholder.typicode.com/posts');
    });
&#13;
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-resource.js"></script>
</head>
<body ng-app="JobsApp">
<div ng-controller="JobController">
    <div>
        <table class="table">
            <tr>
                <th>Job Id</th>
                <th>Description</th>
                <th>Minimum</th>
                <th>Maximum</th>
            </tr>
            <tr ng-repeat="job in Jobs">
                <td>{{job.id}}</td>
                <td>{{job.title}}</td>
                <td>{{job.userId}}</td>
                <td></td>
            </tr>
        </table>
    </div>
</div>
</body>
</html>
&#13;
&#13;
&#13;