For better capsulation I want to create a new type that includes multiple other types. entityService
should be typed as OakService
or MapleService
which should be included inside TreeService
.
One possible solition you can see inside the comments. If I uncomment the imports inside garden.component.ts and replace TreeService
with OakService | MapleService
OakService | MapleService
, it will work, but I want some kind of parent type, that includes them all.
tree.service.ts
import { OakService } from './oak.service';
import { MapleService } from './maple.service';
export type TreeService = typeof OakService | MapleService;
oak.service.ts
import { BaseService } from './base.service';
@Injectable()
export class OakService extends BaseService {
constructor() {
super();
}
}
maple.service.ts
import { BaseService } from './base.service';
@Injectable()
export class MapleService extends BaseService {
constructor() {
super();
}
}
garden.component.ts
// import { OakService } from './oak.service';
// import { MapleService } from './maple.service';
import { TreeService } from './parent.service';
@Component()
export class GardenComponent {
constructor(
protected entityService: TreeService // OakService | MapleService
) {}
}
balcony.component.ts
import { MapleService } from './maple.service';
export class BalconyComponent extends GardenComponent {
constructor(
protected mapleService: MapleService
) {
super(mapleService);
}
}
Info: The code above does not work. Your have to use the code inside the comments. The error I've got is not inside balcony.component.ts : ERROR in : Can't resolve all parameters for BaseListComponent in .../garden.component.ts: (?).
Parameter types in injectable class allow to skip Angular @Inject
decorator in TypeScript and annotate a constructor for dependency injection. Types don't exist at runtime and cannot be injected.
GardenComponent
cannot be workable component because of that. Since is used as abstract class, it shouldn't have @Component
decorator:
export abstract class GardenComponent {
constructor(
protected entityService: TreeService // OakService | MapleService
) {}
}
While child classes should have @Component
:
@Component(...)
export class BalconyComponent extends GardenComponent {
constructor(mapleService: MapleService) {
super(mapleService);
}
}
Constructors are mandatory in child classes because parent class doesn't contain proper annotation, and their parameters shouldn't have visibility modifiers because this.entityService
is already assigned by parent constructor.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.