使用 Angular 中的服务
Use a service in Angular
当我尝试在我的应用程序的控制器中使用 Angular 服务时遇到了一些问题。
当我尝试在我的控制器中使用我的服务功能时,我的控制台向我抛出一个错误:/
var app = angular.module('app', ['ngRoute'])
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/login', {
controlleur: 'login',
templateUrl: 'modules/login/login.html'
})
.otherwise({
redirectTo: '/login'
});
}]);
app.service('coreServices', [function () {
this.helloConsole = function () {
console.log("console services");
};
}]);
app.controller('loginController', ['$scope', '$http', '$rootScope', '$location', 'coreServices', LoginController]);
function LoginController($scope, $http, $rootScope, coreServices) {
var vm = this;
vm.helloConsole = coreServices.helloConsole;
vm.helloConsole();
}
angular.js:13708 TypeError: vm.helloConsole is not a function
at new LoginController
我link你这个fiddle向你展示我是怎么做的:https://jsfiddle.net/h8yaxLap/2/
抛出的错误是:
angular.js:13708 TypeError: vm.helloConsole 不是函数
在新的登录控制器
好吧,在您的示例中,angular 会将 $location
映射到函数注入参数中的 coreService。所以我会选择
app.controller('loginController', ['$scope', '$http', '$rootScope', '$location', 'coreServices', LoginController]);
function LoginController($scope, $http, $rootScope, $location, coreServices)
将服务函数更改为 return 对象
app.service('coreServices', function () {
return {
helloConsole: function () {
console.log("console services");
}
};
});
您错过了控制器的 $location 参数
函数 LoginController($scope, $http, $rootScope,$location, coreServices)
当我尝试在我的应用程序的控制器中使用 Angular 服务时遇到了一些问题。
当我尝试在我的控制器中使用我的服务功能时,我的控制台向我抛出一个错误:/
var app = angular.module('app', ['ngRoute'])
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/login', {
controlleur: 'login',
templateUrl: 'modules/login/login.html'
})
.otherwise({
redirectTo: '/login'
});
}]);
app.service('coreServices', [function () {
this.helloConsole = function () {
console.log("console services");
};
}]);
app.controller('loginController', ['$scope', '$http', '$rootScope', '$location', 'coreServices', LoginController]);
function LoginController($scope, $http, $rootScope, coreServices) {
var vm = this;
vm.helloConsole = coreServices.helloConsole;
vm.helloConsole();
}
angular.js:13708 TypeError: vm.helloConsole is not a function
at new LoginController
我link你这个fiddle向你展示我是怎么做的:https://jsfiddle.net/h8yaxLap/2/
抛出的错误是: angular.js:13708 TypeError: vm.helloConsole 不是函数 在新的登录控制器
好吧,在您的示例中,angular 会将 $location
映射到函数注入参数中的 coreService。所以我会选择
app.controller('loginController', ['$scope', '$http', '$rootScope', '$location', 'coreServices', LoginController]);
function LoginController($scope, $http, $rootScope, $location, coreServices)
将服务函数更改为 return 对象
app.service('coreServices', function () {
return {
helloConsole: function () {
console.log("console services");
}
};
});
您错过了控制器的 $location 参数 函数 LoginController($scope, $http, $rootScope,$location, coreServices)