使用路由的未定义服务控制器

Undefined service controller using route

我正在将 angular 服务与我的服务文件分开的路由一起使用。 我在 Plunker code 的 console.See 代码中遇到 branchService is undefined 错误 这里是 branchService.js:

 angular.module("myApp").service('branchService', ['$http', function ($http) {
    var link = "http://localhost:8008/";
    //----Get Dining Tables`enter code here`
    this.getBranches = function ($scope) {
        return $http({
            method: "GET",
            url: encodeURI(link + "Branch/GetBranches/"),
            headers: { 'Content-Type': 'application/json' }
        }).success(function (data) {
            console.log(data);
        }).error(function (data) {
            console.log(data);
        });
    };
}]);

和myController.js在这里:

var app = angular.module("myApp", ['ngRoute']);

app.config(function ($routeProvider) {
    $routeProvider
        .when('/branches', {
            templateUrl: 'branches.html',
            controller: 'branchController'
        })

        .otherwise({
            redirectTo: '/branches'
        });
});

app.controller('branchController', ['$scope', '$filter', 'branchService', function ($scope, $filter, branchService) { 
  branchService.getBranches($scope);
}

当我运行错误:$injector:modulerr Module Error 错误显示在控制台

您是否在 index.html 或任何第一页中添加了对 branchService.js 文件的引用。

请尝试在您的 myController.js 之后添加引用。

在使用该服务之前先注入它,以便您可以使用它

var app = angular.module("myApp", ['ngRoute', 'branchService']);

编辑:

这是branchController.js中的问题:

var app = angular.module("myApp", ['ngRoute']);

您再次注入了 ngRoute 实际上您已经将其添加到 app.js :

var app = angular.module("myApp",['ngRoute']);

修复:删除 ng 路由

var app = angular.module("myApp");

你必须这样做。您的服务应该在您的控制器之前首先加载。

var app = angular.module("myApp", ['ngRoute']);

app.config(function ($routeProvider) {
    $routeProvider
        .when('/branches', {
            templateUrl: 'branches.html',
            controller: 'branchController'
        })

        .otherwise({
            redirectTo: '/branches'
        });
});

app.service('branchService', ['$http', function ($http) {
    var link = "http://localhost:8008/";
    //----Get Dining Tables`enter code here`
    this.getBranches = function ($scope) {
        return $http({
            method: "GET",
            url: encodeURI(link + "Branch/GetBranches/"),
            headers: { 'Content-Type': 'application/json' }
        }).success(function (data) {
            console.log(data);
        }).error(function (data) {
            console.log(data);
        });
    };
}]);

app.controller('branchController', ['$scope', '$filter', 'branchService', function ($scope, $filter, branchService) { 
  branchService.getBranches($scope);
}