简体   繁体   中英

Injecting service into controller throws error

I am unable to inject service into controller. I was able to execute a similar code a year ago and it worked but this time I am having a hard luck.

app.js

'use strict';
var app = angular.module('product', [
  "ngRoute",
]);

main.ctrl.js

'use strict';
app.controller('mainCtrl', ['$scope','$http','srv', function ($scope,$http,srv) {
    var srvUrl = srv.getSrvUrl;
    var data = srv.getData(1,2);
}]);

srv.js

app.service("srv", function ($http,$scope) {
    this.getSrvUrl = "http://127.0.0.1/api/";
    this.getData = function(a,b) { return a*b; }
});

index.html

<!--JS-->
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
<!--APP-->
<script type="text/javascript" src="app/app.js"></script>
<!-- ROUTE -->
<script type="text/javascript" src="bower_components/angular-route/angular-route.min.js"></script>
<script type="text/javascript" src="app/routes/app.route.js"></script>
<!-- SERVICE -->
<script type="text/javascript" src="app/services/srv.js"></script>
<!--CONTROLLER-->
<script type="text/javascript" src="app/controllers/main.ctrl.js"></script>

console error

angular.js:14362 
Error: [$injector:unpr] http://errors.angularjs.org/1.6.2/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20srv
at angular.js:38
at angular.js:4650
at Object.d [as get] (angular.js:4803)
at angular.js:4655
at d (angular.js:4803)
at e (angular.js:4828)
at Object.instantiate (angular.js:4874)
at Object.<anonymous> (angular.js:4712)
at Object.invoke (angular.js:4862)
at Object.$get (angular.js:4696)

Please help.

You can not inject $scope in service.

Service are singleton object used to share data and some reusable methods.

It should be like this

app.service("srv", function ($http, $scope) {
    return {
        getSrvUrl: "http://127.0.0.1/api/",
        getData: function (a, b) { return a * b; }
    }
});

The only scope you can inject in a service is $rootScope (but given your code, I'm not sure you need a scope at all in the service). Also, you'll probably want to add the service names as strings for minification:

app.service("srv", ['$http', '$rootScope', function ($http, $rootScope) {
    // ...
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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