简体   繁体   English

Angular Service已注入控制器,但它显示为空对象

[英]Angular Service is injected into controller, but it appears as an empty object

I have the following angular service. 我有以下角度服务。

angular.module('myApp')
.service('StatusService', function StatusService() {
    var statusService= {
        show: 'off',
        on: function() {
            this.show = 'on';
        },
        off: function() {
            this.show = 'off';
        }
    };

    return statusService;
});

Which is injected into a controller, and its on function is invoked, like this: 将其注入到控制器中,并调用其on函数,如下所示:

angular.module('myApp')
    .controller('aController', function (StatusService) {

    StatusService.on(); 
})

But I get the following error. 但是我收到以下错误。

TypeError: Object #<Object> has no method 'on'

I think you're using a module.service() invocation with module.factory() implementation when declaring the service. 我认为您在声明服务时正在对module.factory()实现使用module.service()调用。 either change the earlier to module.factory(StatusService) (which should really be called StatusServiceFactory ) OR change impl to add interface methods to StatusService itself ie: 可以将较早的版本更改为module.factory(StatusService) (应真正称为StatusServiceFactory ),或者更改impl以向StatusService本身添加接口方法,即:

function StatusService(){
this.show='off';
this.on = function(){};
}
module.service('statusService', StatusService);

Here's a demo of the above working: http://plnkr.co/edit/r07kPP85oQQKtJYMYOyK?p=preview 这是上述工作的演示: http : //plnkr.co/edit/r07kPP85oQQKtJYMYOyK?p=preview

如果您在不同的地方声明了多个具有相同名称的服务,就会出现此问题,它会造成混乱并返回{}。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM