Angular 如何在不注射祖父母的情况下注射孙子服务
我想在根模块中注入孙子服务,如下所示:Angular 如何在不注射祖父母的情况下注射孙子服务,angular,dependency-injection,angular2-services,Angular,Dependency Injection,Angular2 Services,我想在根模块中注入孙子服务,如下所示: providers:[MyAppTables] @Injectable() export class TableBase { protected _items: BehaviorSubject<any[]> = new BehaviorSubject([]); public items: Observable<any[]> = this._items.asObservable(); constructor(){
providers:[MyAppTables]
@Injectable()
export class TableBase {
protected _items: BehaviorSubject<any[]> = new BehaviorSubject([]);
public items: Observable<any[]> = this._items.asObservable();
constructor(){
this.init([]);
}
init(newItems:any[]) {
this._items.next(newItems);
}
}
@Injectable()
export class TableProducts extends TableBase {
constructor(@Inject(TableBase) __base: any ){
super();
}
init() {
super.init([{id:1,name:'A'},{id:2,name:'B'}]);
}
}
@Injectable()
export class MyAppTables{
public products: Observable<any[]>;
constructor(@Inject(TableProducts) prod: any ){
this.products = prod.items;
}
}
我的服务结构如下:
providers:[MyAppTables]
@Injectable()
export class TableBase {
protected _items: BehaviorSubject<any[]> = new BehaviorSubject([]);
public items: Observable<any[]> = this._items.asObservable();
constructor(){
this.init([]);
}
init(newItems:any[]) {
this._items.next(newItems);
}
}
@Injectable()
export class TableProducts extends TableBase {
constructor(@Inject(TableBase) __base: any ){
super();
}
init() {
super.init([{id:1,name:'A'},{id:2,name:'B'}]);
}
}
@Injectable()
export class MyAppTables{
public products: Observable<any[]>;
constructor(@Inject(TableProducts) prod: any ){
this.products = prod.items;
}
}
我的问题是:有更好的方法来注射吗
注意:这个示例只显示了一个父类,其思想是抽象祖父母类中的基本代码,为每个表创建一个父类,并在需要的地方包含该服务您所说的孙子服务是什么意思classC(孙子)扩展classB,classB扩展classA(祖父母)。Angular2需要一个提供者(或者是注入式的,我是新来的)提供所有的服务,你这样写服务吗?相互扩展?就在这种情况下,我不必在所有12个服务中复制相同的代码您确定需要继承才能在服务之间共享代码吗?您不能通过创建帮助器模块/函数/类来实现同样的功能吗?