Search code examples
javascriptnode.jsangularjstoastr

How to inject angular services correctly


I created a service called notifier that use toastr to alert the user during the log in process if the user successfully logged in or not.

here is my log in module:

var login = angular.module('login',[]);

    login.controller('mvLoginCtrl', function($scope, $http){
        $scope.signin = function(username, passowrd){
            $http.post('/login', {username:username, passowrd:passowrd}).then(function(response){
                if(response.data.success){
                    mvNotifier.notify('You have successfully signed in!');
                }else{
                    mvNotifier.notify('Username/Password combination incorrect');
                }
            })
        }
    })

i got no errors till here but when i try to sign in i get this obvious error :

ReferenceError: mvNotifier is not defined

i changed my log in module at the line 2 including the required dependencies:

login.controller('mvLoginCtrl', function($scope, $http, mvNotifier) 

but then i got different error

Error: [$injector:unpr] http://errors.angularjs.org/1.2.20/$injector/unpr?p0=mvIdentityProvider%20%3C-%20mvIdentity

and i want to ask what is the reason i got this error and how to solve it. here is my mvNotifier module code:

var notifier = angular.module('notifier', []);

    notifier.value('mvToastr', toastr);
    notifier.factory('mvNotifier', function(myToastr){
        return{
            notify: function(msg){
                mvToastr.success(msg);
                console.log(msg);
            }
        }
    })

thank you.


Solution

  • You need to inject myNotifier something like this:

    var login = angular.module('login',['notifier']);
    
        login.controller('mvLoginCtrl', ['$scope','$http','mvNotifier',function($scope, $http,mvNotifier){
            $scope.signin = function(username, passowrd){
                $http.post('/login', {username:username, passowrd:passowrd}).then(function(response){
                    if(response.data.success){
                        mvNotifier.notify('You have successfully signed in!');
                    }else{
                        mvNotifier.notify('Username/Password combination incorrect');
                    }
                })
            }
        }])
    

    More on Dependency Injection