另一个变体使用@Inject
装饰器,如果条件计算在当前类之外。
export interface IService {
test: string;
}
@Injectable()
export class Serivce1 implements IService {
test: 'service1';
}
@Injectable()
export class Serivce2 implements IService {
test: 'service2';
}
const CONDITION = Math.random() > 0.5;
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
constructor(@Inject(CONDITION ? Serivce1 : Serivce2) private service: IService) {
console.warn(service);
}
}