如何在Angular服务方法中调用函数?

时间:2017-05-10 16:11:55

标签: angularjs

如果我在Angular服务中调用了一个方法,我怎么能在这个方法中调用一个方法?在驻留在服务中的方法内部创建函数是否合适?以下是一个例子。被调用的函数modalSuccess不会触发。此外,尝试使用$ scope或$ rootScope失败,同时调用服务名称,然后使用last.successModal()等新方法。

angular.module('main').service('last', function($location, $http)
{
    this.submit = function(){
        function modalSuccess(){
           console.log('hello world'); 
        }
        modalSuccess() --> does not fire
}

$ rootScope示例不起作用

angular.module('main').service('last', function($location, $http, $rootScope)
{
    this.submit = function(){
     $rootScope.modalSuccess = function(){
           console.log('hello world'); 
        }
       $rootScope.modalSuccess() --> does not fire
}

即使添加新方法也无效

angular.module('main').service('last', function($location, $http, $rootScope)
{
    this.submit = function(){
     this.modalSuccess = function(){
       console.log('hello world'); 
     }
      last.modalSuccess() --> does not fire, returns an error
}

2 个答案:

答案 0 :(得分:1)

第一个示例看起来正确,除了您没有关闭提交函数的花括号(这应该导致错误)。

//1° example
angular.module('main').service('last', function($location, $http)
{
    this.submit = function(){
        function modalSuccess(){
           console.log('hello world'); 
        }
        modalSuccess() --> does not fire

   }//you missed this curly braces
}

第二个例子与上面相同,花括号未关闭

第三个例子应该抛出一个错误,因为上面因为你正在尝试使用为角色进行依赖注入保留的关键字来访问自身内部的服务。

//3° example
angular.module('main').service('last', function($location, $http, $rootScope)
{
    this.submit = function(){
     this.modalSuccess = function(){
       console.log('hello world'); 
     }
      last.modalSuccess() //this is not possible, you cannot refer the 
      //service with 'last' keyword here, but use 'this' as you did above

    } //curly braces missing here
}

答案 1 :(得分:0)

您永远不会将该功能分配给任何东西。另外,为什么在函数中声明一个函数,这似乎是反直觉的。

angular.module('main').service('last', function($location, $http)
{
    this.submit = function(){
        var modalSuccess = function(){
           console.log('hello world'); 
        }
        modalSuccess(); // <= should now work
    }
}

或者

angular.module('main').service('last', function($location, $http)
{
    var me = this; // using me as this can change depending on the call context if you are referencing it inside of a method
    me.modalSuccess = function() {
       console.log('hello world'); 
    };

    me.submit = function(){
        me.modalSuccess(); // <= should now work
    }
}