Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何在不注射祖父母的情况下注射孙子服务_Angular_Dependency Injection_Angular2 Services - Fatal编程技术网

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个服务中复制相同的代码您确定需要继承才能在服务之间共享代码吗?您不能通过创建帮助器模块/函数/类来实现同样的功能吗?