简体   繁体   中英

AngularJS Service breaking Controller

I'm trying to implement some services on my Angular v1.6.4 app. However I get this error 我的错误 when I import the service in my index.html

This is the content of my service

angular.module('myApp', [])
.service('SessionService', function() {
    $this.get = function () {
         return true;
    }
 });

I didn't even used it in my app. Simply importing it like

<script src="path/to/SessionService.js"></script>

already brings the error up

As of the home controller, I implemented it like this:

angular.module('myApp', [])
.controller('home', ['$scope', function($scope) {

}]);

And I called it like

<header class="navbar" ng-controller="home"></header>

I also made sure I was importing the home controller in my index.html.

I just can't get what I'm missing out. Could you help me, please ? Thanks in advance!!!

angular.module('myApp', []) means you are creating the module myApp , and you are doing it twice.

create once the module using angular.module('myApp', []) by passing a second argument ( [] : array of dependent modules) and for referring the module next time onward, use

angular.module('myApp') //this will return an reference to the existing module myApp

and btw, it will be this inside service and not $this

change the first line inside your service file

angular.module('myApp', [])
.service('SessionService', function() {
    $this.get = function () {
         return true;
    }
 });

should be

angular.module('myApp')
.service('SessionService', function() {
    $this.get = function () {
         return true;
    }
 });

without the []

When you use the square bracket inside angular.module, you redefine a new module. Without you access an existing module

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