[英]error when injecting service in controller
I am trying to consume Web API using AngularJs but getting struck angular side which is hard for me to figure out. 我正在尝试使用AngularJs来使用Web API,但是受到了角度方面的攻击,这对我来说很难理解。
I created HTML, controller and service. 我创建了HTML,控制器和服务。 Everything seems ok to me but when running the app i get the injection error. 一切似乎都没问题,但在运行应用程序时我得到了注射错误。
html
<html >
<head>
<title>Motors </title>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-route.js"></script>
<script src="/View/motorController.js"></script>
</head>
<body ng-app="myApp" ng-controller="motorController">
<div>
<table class="table">
<tr>
<th>Id</th>
<th>Name</th>
<th>Country</th>
</tr>
<tr ng-repeat="m in motors">
<td>{{m.Id}}</td>
<td>{{m.Name}}</td>
<td>{{m.Country}}</td>
</tr>
</table>
</div>
</body>
</html>
AngularJs controller AngularJs控制器
var module = angular.module('myApp', [])
.controller('motorController', ['$scope', '$motorService',function ($scope, motorService) {
getMotors();
function getMotors() {
motorService.GetAllMotors()
.success(function (motors) {
$scope.motors = motors;
})
.error(function (error) {
$scope.status = 'Unable to load motor data: ' + error.message;
});
}
}]);
angular service 角度服务
motorApp.factory('motorService', function ($http) {
var urlBase = 'http://localhost:40738/api';
var motorService = {};
motorService.GetAllMotors = function () {
return $http.get(urlBase + '/GetAllMotors');
};
return motorService;
});
Error i am getting on chrmoe browser console 我在chrmoe浏览器控制台上出错了
Error: [$injector:unpr] Unknown provider: $motorServiceProvider <- $motorService <- motorController
You have a extra $ infront of MotorService, change 你有一个额外的$前面的MotorService,改变
From: 从:
.controller('motorController', ['$scope', '$motorService',function ($scope, motorService)
To: 至:
.controller('motorController', ['$scope', 'motorService',function ($scope, motorService)
The problem with your code is that the factory is given a different module name " motorApp
" instead of module name " module
". 您的代码的问题是工厂被赋予了不同的模块名称“ motorApp
”而不是模块名称“ module
”。
Use 采用
module.factory('motorService', function ($http) { //change here
var urlBase = 'http://localhost:40738/api';
var motorService = {};
motorService.GetAllMotors = function () {
return $http.get(urlBase + '/GetAllMotors');
};
return motorService;
});
Also in your controller you should remove the "$" from injected service name " motorService
" 同样在你的控制器中你应该从注入的服务名称“ motorService
”中删除“$”
var module = angular.module('myApp', [])
.controller('motorController', ['$scope', 'motorService',function ($scope, motorService) {
getMotors();
function getMotors() {
motorService.GetAllMotors()
.success(function (motors) {
$scope.motors = motors;
})
.error(function (error) {
$scope.status = 'Unable to load motor data: ' + error.message;
});
}
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.