假设我有一个 crudService.js 文件:
crudService.module('genericCrudService', ['$http', '$log', 'config', function ($http, $log, config) {
....
return {
setSomeAttribute: function(m) {
// set attribute
}
}
}]);
然后我有一个模块需要对此 CRUD 服务进行不同配置的实例:
module.factory('Task', ['genericCrudService','genericCrudService', function (service, actionService) {
...
return {
init: function(p) {
service.setSomeAttribute('a');
actionService.setSomeAttribute('b');
}
}
}]);
但是后来我注意到,当尝试使用 service 变量时,它的属性设置为“a”。我做错了什么?
最佳答案
Angular 服务 are singletons在第一次注入(inject)时缓存:
All services in Angular are singletons. That means that the injector uses each recipe at most once to create the object. The injector then caches the reference for all future needs.
genericCrudService
引用相同的服务,将其注入(inject)为 service
和 actionService
变量会产生 genericCrudService
的实例两个变量中的 code> service,service === actionService
。
如果服务仅在某些情况下应该获取新实例,则服务实例可能会获取返回对象新实例的方法(例如 factory
或 getInstance
) :
app.factory('service', () => {
function Service() {
this.method = ...;
this.factory = () => new Service;
}
return new Service;
});
...
var serviceInstance = service.factory();
如果服务应该在任何地方获取新实例,它应该返回一个将手动实例化的工厂或构造函数:
app.factory('Service', () => function () {
this.method = ...;
});
...
var serviceInstance = new Service;
关于javascript - 如何在 AngularJs 中注入(inject)模块的 2 个不同实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38573564/