AngularJS)TypeError:serviceName.functionName()不是函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AngularJS)TypeError:serviceName.functionName()不是函数相关的知识,希望对你有一定的参考价值。

我想做“取消点击后返回”功能。

这是视图代码

<div ng-controller="goodCtrl">    
<button class="btn" ng-click="cancel()">Cancel</button>
</div>

这是Js代码

1)控制器

function goodCtrl($scope, $log, goodService)
    $scope.cancel = function(){
        $log.debug("goodCtrl - cancel");
        goodService.cancel($scope);
    };

2)服务

function goodService($log, $state)
    var methods = {
       cancel: function($scope) {
           $log.debug("goodService - cancel");
           $state.go('goback');
       }
    }

3)模块

angular
    .module('goodmodule')
    .controller('goodCtrl', goodCtrl)
    .service('goodService', goodService)

但是我遇到了这个问题

TypeError:serviceName.functionName()不是函数

虽然有这么多的控​​件,服务,方法,但我添加的服务和控制器都不可用。我错过了什么?

答案

正如你已经使用service定义了要暴露的this寄存器方法

function goodService($log, $state) {
    this.cancel = function ($scope) {
        $log.debug("goodService - cancel");
        $state.go('goback');
    }
}

我还建议你使用Dependency Annotation,这里我使用了$inject属性注释

 goodCtrl.$inject = ['$scope', '$log', 'goodService'];
 goodService.$inject = ['$log', '$state'];
另一答案

在angularjs中,要定义服务,您必须在服务函数中为此关键字指定属性。因为在角度js中构造函数用于创建自定义服务.Below代码是您更新的服务代码。

    function goodService($log, $state) {
    this.cancel = function ($scope) {
        $log.debug("goodService - cancel");
        $state.go('goback');
    }
}

以上是关于AngularJS)TypeError:serviceName.functionName()不是函数的主要内容,如果未能解决你的问题,请参考以下文章

AngularJS - TypeError: v2.[xxxx] 不是函数

AngularJS 错误:TypeError:v2.login 不是函数

Angularjs - TypeError:路径必须是绝对路径或指定根到 res.sendFile

AngularJS指令元素方法绑定-TypeError:无法使用'in'运算符在1中搜索'functionName'

未捕获(承诺):TypeError:无法读取未定义的属性“创建”(离子 3.9,Angularjs 5.0.3)

angularJs TypeError:将循环结构转换为JSON