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

Undefined service controller using route

本文关键字:服务 控制器 未定义 路由      更新时间:2023-09-26

>我正在使用角度服务与路由,其中我的服务文件是分开的。我面对分支服务是控制台中未定义的错误。查看 Plunker 代码中的代码这是分支服务.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:模块rr控制台中显示模块错误错误

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

只需尝试在 myController.js 之后添加引用即可。

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

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

编辑:

这是分支控制器中的问题.js:

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

您再次注入ngRoute实际上您已经将其添加到应用程序中.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);
}