angular 仅提供 singleton 服务/工厂选项。
解决它的一种方法是拥有一个工厂服务,它将在您的控制器或其他消费者实例中为您构建一个新实例。
唯一注入的是创建新实例的类。
这是注入其他依赖项或根据用户规范初始化新对象(添加服务或配置)的好地方
namespace admin.factories {
'use strict';
export interface IModelFactory {
build($log: ng.ILogService, connection: string, collection: string, service: admin.services.ICollectionService): IModel;
}
class ModelFactory implements IModelFactory {
// any injection of services can happen here on the factory constructor...
// I didnt implement a constructor but you can have it contain a $log for example and save the injection from the build funtion.
build($log: ng.ILogService, connection: string, collection: string, service: admin.services.ICollectionService): IModel {
return new Model($log, connection, collection, service);
}
}
export interface IModel {
// query(connection: string, collection: string): ng.IPromise<any>;
}
class Model implements IModel {
constructor(
private $log: ng.ILogService,
private connection: string,
private collection: string,
service: admin.services.ICollectionService) {
};
}
angular.module('admin')
.service('admin.services.ModelFactory', ModelFactory);
}
然后在您的消费者实例中,您需要工厂服务并在需要时调用工厂上的构建方法以获取新实例
class CollectionController {
public model: admin.factories.IModel;
static $inject = ['$log', '$routeParams', 'admin.services.Collection', 'admin.services.ModelFactory'];
constructor(
private $log: ng.ILogService,
$routeParams: ICollectionParams,
private service: admin.services.ICollectionService,
factory: admin.factories.IModelFactory) {
this.connection = $routeParams.connection;
this.collection = $routeParams.collection;
this.model = factory.build(this.$log, this.connection, this.collection, this.service);
}
}
您可以看到它提供了注入一些在工厂步骤中不可用的特定服务的操作。
您始终可以在工厂实例上进行注入,以供所有模型实例使用。
注意我必须去掉一些代码,这样我可能会犯一些上下文错误......
如果您需要有效的代码示例,请告诉我。
我相信 NG2 可以选择在 DOM 中的正确位置注入新的服务实例,因此您无需构建自己的工厂实现。将不得不拭目以待:)