从同一服务调用 AngularJS 服务中的函数?
我有一个以下列方式定义的 AngularJS 服务
I have an AngularJS service defined in the following way
angular.module('myService').service('myService', function() {
this.publicFunction(param) {
...
};
this.anotherPublicFunction(param) {
// how to call publicFunction(param)?
...
};
});
我想从服务外部调用第一个函数(通过 myService.publicFunction(xxx)
可以正常工作)和同一服务中的另一个函数,即 anotherPublicFunction代码>.
this.publicFunction(param)
或 myService.publicFunction(param)
都不能在第二个函数中工作,我可以理解.
and I would like to call the first function both from outside the service (which works fine by myService.publicFunction(xxx)
) and from another function in the same service, i.e. anotherPublicFunction
. Neither one of this.publicFunction(param)
or myService.publicFunction(param)
won't work from within the second function, and I can understand that.
实际上,整个问题都是由您无法仅用我的示例重现的东西引起的.我将第二个函数作为回调参数传递给单独控制器中的另一个函数,当它被调用时,对 this
的引用不起作用.
Actually the whole problem was caused by something you can't reproduce with my example alone. I passed the second function as a callback parameter to another function in a separate controller, and when it is called, the reference to this
doesn't work.
例如
anotherService.someCall('a', 123, myService.anotherPublicFunction);
在 anotherPublicFunction
中失败,因为 this
无法解析.
fails inside anotherPublicFunction
because this
can't be resolved.
我写了一个Plunker来说明这个问题:http://plnkr.co/edit/rrRs9xnZTNInDVdapiqF?p=info
(我还是把问题留在这里,以防它对其他人有帮助.)
我知道我可以通过使用对服务的引用或像这样的第一个函数来解决这个问题
I know I could get around the problem by using a reference to the service or the first function like this
var ms = this;
this.anotherPublicFunction(param) {
ms.publicFunction(param);
...
};
或者这个
var pf = this.publicFunction;
this.anotherPublicFunction(param) {
pf(param);
...
};
但两者看起来都是肮脏的黑客.
but both seem like dirty hacks.
在这种情况下,有没有一种从第二个函数调用第一个函数的好方法?或者我是否一开始就做错了什么以获得这样的服务?
我发现这些问题的答案很好:
I found these questions with good answers:
但它们与我的问题不同,因为其中一个有一个单独的内部函数要调用,另一个使用工厂而不是服务.
but they differ from my problem since one of them has a separate, internal function that was to be called, and the other one was using a factory instead of a service.
发布此内容后,我立即意识到我也可以这样做:
After posting this I immediately realized I could also do this:
var actualWork = function(param) {
...
}
this.publicFunction(param) {
actualWork(param);
};
this.anotherPublicFunction(param) {
actualWork(param);
...
};
到目前为止,这似乎不像其他选项那么糟糕......有更好的方法吗?
which doesn't seem quite as bad as the other options so far... Are there better approaches?
我认为最好的方法是这样:
I think the best way is to go like this:
var myFunctions =
{
myFunc1: function(param) {
},
myFunc2: function(param) {
return foo + myFunctions.myFunc1(param)// do some stuff with the first function
}
}
return myFunctions;
因为我认为如果您使用this,它可能会与您使用该服务的范围发生冲突.
because I think if you use this, it may get conflict with the scope where you use the service.