首页 > 解决方案 > 是否可以以子类不必在构造函数中传递路由器的方式在父类中注入路由器?

问题描述

我有一个 带有依赖项 Http、Router 的service.ts并被注入到 parent.ts中。

child.ts需要扩展父类,但不应该为在构造函数中传递服务而烦恼。为了实现这一点,我尝试了方法 (a)来实现父类而不是受信任的方法 (b),并使用 @NgModule 装饰器向 app.module.ts 中的提供者添加服务。

问题:我无法使用方法 (a)创建注入器

服务.ts

@Injectable()
export class Service {
  constructor(private http: Http,
    private router:Router
    ) {}
}

父.ts

方法(一)

export class Parent {
serv:Service
constructor(private name: string) {
const injector = Injector.create({
       providers:
           [{provide: Service, deps: [Http,Router]}, {provide:Http, deps:[]}, {provide: 
Router, deps:[]}]
         })
this.serv = injector.get(Service)
}
}

方法(b)

import { Router } from '@angular/router';
    export class BasetaskComponent {
    constructor(private name: string, private router : Router) {}
}

child.ts

export class Child extends Parent {
constructor() {
super('name')
}

标签: angulardependency-injection

解决方案


推荐阅读