Angular 如何将派生类作为服务注入
我想将我的组件使用的服务的接口与其实现分离,以简化能够手工制作的mock的创建,这种情况经常发生,并将实现作为使用它的组件的依赖项注入。这种方法是Java弹性后端的常见方法 如果我有这样的代码:Angular 如何将派生类作为服务注入,angular,dependency-injection,derived-class,Angular,Dependency Injection,Derived Class,我想将我的组件使用的服务的接口与其实现分离,以简化能够手工制作的mock的创建,这种情况经常发生,并将实现作为使用它的组件的依赖项注入。这种方法是Java弹性后端的常见方法 如果我有这样的代码: export abstract class AbstractMyService {// Defines the interface of the service ... } export class MyService extends AbstractMyService {// The conc
export abstract class AbstractMyService {// Defines the interface of the service
...
}
export class MyService extends AbstractMyService {// The concrete implementation
...
}
@Component({
selector: 'app-myComponent',
templateUrl: './my.component.html',
styleUrls: ['./my.component.css']
})
export class MyComponent implements OnInit {
constructor(
private readonly service: AbstractMyService) {
}
...
}
我如何确保在应用程序中实例化MyComponent时,它会将MyService类型的对象传递给其构造函数
我知道,如果我不分离接口和实现,那么MyService是一个具体的类,AbstractMyService不存在,我可以这样做:
@Injectable({
providedIn: 'root'
})
export class MyService {
...
}
我是否只需要将MyService注释为@Injectable?或者我必须做一些更复杂的事情吗?您应该明确地将实现声明为提供者
@NgModule({ // or @Component, depending on the place you want to configure.
....
providers: [{
provide: AbstractMyService,
useClass: MyService
}]
})
没有办法像在Spring中那样自动检测。该配置明确表示,如果有东西使用令牌AbstractMyService注入项,则类MyService将用作构造函数
在希望所有组件使用同一个具体类的常见情况下,应该为AppModule声明该提供程序。对于单元测试,您可以将提供程序声明为测试台配置的一部分:
TestBed.configureTestingModule({
declarations: [MyComponent],
providers: [
...
{ provide: AbstractMyService, useFactory: () => { return new MockMyService(...); } }]
});