javascript - 如何正确注入(inject) Angular 服务

标签 javascript node.js angularjs toastr

我创建了一个名为 notifier 的服务,它使用 toastr 在登录过程中提醒用户是否成功登录。

这是我的登录模块:

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');
                }
            })
        }
    })

到目前为止我没有收到任何错误,但是当我尝试登录时,我收到了这个明显的错误:

ReferenceError: mvNotifier is not defined

我在第 2 行更改了登录模块,包括所需的依赖项:

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

但是后来我得到了不同的错误

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

我想问一下我收到此错误的原因是什么以及如何解决它。 这是我的 mvNotifier 模块代码:

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

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

谢谢。

最佳答案

您需要注入(inject) myNotifier ,如下所示:

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');
                }
            })
        }
    }])

更多关于Dependency Injection

关于javascript - 如何正确注入(inject) Angular 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25214933/

相关文章:

javascript - 使用 Elasticsearch 的 Ajax 查询格式

javascript - XMLHttpRequest 不适用于 react native 应用程序

javascript - 安装 Gulp : “no command ' gulp' found” 后

angularjs - ngGrid 2.0.14 行选择不适用于新版 Google Chrome 和 ngAnimate

mysql - 为 AngularJS 驱动的学习页面存储数据的正确方法是什么

javascript - 使用 AngularJS 在 HTML 标记上执行 if/else

javascript - 预期 xxx 是使用服务后的日期

javascript - jQuery 虚拟键盘插件在 Windows 8 触摸设备上插入相同字符两次

javascript - 中心 table ,即使它比父容器宽

node.js - 在 Node.js 中使用 WebSocket 的最简单方法