繁体   English   中英

在控制器中注入服务时出错

[英]error when injecting service in controller

我正在尝试使用AngularJs来使用Web API,但是受到了角度方面的攻击,这对我来说很难理解。

我创建了HTML,控制器和服务。 一切似乎都没问题,但在运行应用程序时我得到了注射错误。

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控制器

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;
            });
    }
}]);

角度服务

motorApp.factory('motorService', function ($http) {
    var urlBase = 'http://localhost:40738/api';
    var motorService = {};

    motorService.GetAllMotors = function () {
        return $http.get(urlBase + '/GetAllMotors');
    };

    return motorService;
});

我在chrmoe浏览器控制台上出错了

Error: [$injector:unpr] Unknown provider: $motorServiceProvider <- $motorService <- motorController

你有一个额外的$前面的MotorService,改变

从:

 .controller('motorController', ['$scope', '$motorService',function ($scope, motorService) 

至:

 .controller('motorController', ['$scope', 'motorService',function ($scope, motorService)

您的代码的问题是工厂被赋予了不同的模块名称“ motorApp ”而不是模块名称“ module ”。

采用

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;
});

同样在你的控制器中你应该从注入的服务名称“ 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM