答:不能,因为TypeScript的接口是设计时的, JavaScript没有接口。 TypeScript代码从生成的JavaScript过程中消失。没有任何接口类型信息可供Angular在运行时查找。
有两个方案可以实现:
1、方案1:
最简单的解决方案就是定义一个实现接口的抽象类。通常,无论如何你都需要一个抽象类。定义接口:
import {Role} from "../../model/role";export interface ProcessEngine { login(username: string, password: string):string; getRoles(): Role[];}
抽象类:
import {ProcessEngine} from "./process-engine.interface";export abstract class ProcessEngineService implements ProcessEngine { abstract login(username: string, password: string): string; abstract getRoles(): Role[];}
实现类:
import { Injectable } from '@angular/core';import {ProcessEngineService} from "./process-engine.service";@Injectable()export class WebRatioEngineService extends ProcessEngineService { login(username: string, password: string) : string {...} getRoles(): Role[] {...}}
定义provider:
@NgModule({ ... providers: [ ..., {provide: ProcessEngineService, useClass: WebRatioEngineService} ]})
2、方案2:Angular的官方文档建议使用InjectionToken,类似于OpaqueToken。
Your interface and class:
export interface AppConfig { apiEndpoint: string; title: string;}export const HERO_DI_CONFIG: AppConfig = { apiEndpoint: 'api.heroes.com', title: 'Dependency Injection'};
Define your Token:
import { InjectionToken } from '@angular/core';export let APP_CONFIG = new InjectionToken('app.config');
使用InjectionToken对象注册依赖项提供程序
providers: [{ provide: APP_CONFIG, useValue: HERO_DI_CONFIG }]
你可以通过@Inject装饰器将配置对象注入任何需要它的构造函数中:
constructor(@Inject(APP_CONFIG) config: AppConfig) { this.title = config.title;}