以角度向父类注入依赖服务

Mic*_*jas 4 typescript angular

我有课parentchild。在child类扩展parent。我需要@Inject注入类serviceparent因为所有人都child在使用它。我该怎么做?

Goo*_*ian 7

您可以使用类从父Injector级注入任何服务或类,您需要Injector从子级注入该类并将其传递给父级,super(injector)以便父级可以从来自子级的注入器注入您的可重用服务。

父类:

export class BaseComponent implements OnInit {

    protected myService: MyService

    constructor(injector: Injector) {
        this.myService = injector.get(MyService)
    }

    ngOnInit() {
        console.log('ngOnInit from Base');
    }
}
Run Code Online (Sandbox Code Playgroud)

儿童班:

export class AppComponent extends BaseComponent {

  constructor(injector: Injector) {
    super(injector)
  }

  ngOnInit() {
    super.ngOnInit()
    this.myService.getUsers()
  }
}
Run Code Online (Sandbox Code Playgroud)

使用这种方式,您不想将子服务的每个服务都注入到父项中,这样从父项注入更有效。


Kir*_*kin 6

您不能将依赖项注入父类,因为 Angular 不会为您实例化它。它创建了一个你的子类的实例,它也有效地初始化了父类(这不是非常准确,因为类只是语法糖,但它适合这个讨论)。

一种常见的解决方案是将子类设置为可注入,然后使用super. 例如:

class Parent {
    constructor(protected someService: SomeService) { }
}

@Injectable()
class Child extends Parent {
    constructor(someService: SomeService) {
        super(someService);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果Parent实际上并不需要依赖项本身,那么最好只@Injectable()在子类上使用,这些子类可能有自己对依赖项的私有引用。