【发布时间】:2020-01-08 13:21:26
【问题描述】:
我正在开发一个必须使用依赖注入的小角度项目。 我有以下结构:
文件 app.component.html 属于视图,它具有以下指令:
<h1>{{nombreServicio}}</h1>
文件prueba.type.ts,有接口;
export interface PruebaType{
calcularNombre(): string;
}
prueba.service.ts文件是服务,扩展了接口。
import { Injectable } from '@angular/core';
import { PruebaType } from './prueba.type'
@Injectable()
export class PruebaServicio implements PruebaType{
calcularNombre(): string{
return "Andy";
}
}
最后,app.components.ts 文件使用了PruebaServicio 服务的功能,但它不是直接使用PruebaServicio类型的对象>,而不是使用 PruebaType 类型的对象(这是实现 PruebaServicio 类的接口):
import { Component } from '@angular/core';
import { PruebaType } from './service/Prueba.type';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
nombreServicio: string;
constructor(private prueba: PruebaType){
this.nombreServicio = prueba.calcularNombre();
}
}
当我运行应用程序时,我得到了错误:
无法解析 AppComponent 的所有参数:(?)
想问一下,TypeScript 是否有办法在依赖注入中使用多态性。
感谢您的帮助。
问候。
------------------------------------------已添加--------------------------------
我用Interfaces, TypeScript and Dependency Injections找到了关于多态性的解释:
由于接口不是 JavaScript 的一部分,它们就会消失 编译 TypeScript 后。没什么新鲜的,但这意味着我们 不能使用接口进行依赖注入
然后,在 TypeScript 中进行多态的唯一方法是不使用抽象类或像 Miguel Pinto 在下面的回复中所说的抽象类。 有人认为不同吗?
【问题讨论】:
-
看看注入令牌
-
嗨'dcg',感谢您的回答,我找到了一些使用类依赖注入的示例,但是,我还没有看到任何使用接口的示例。我还在一些论坛中发现,我可以使用以下代码解决错误:构造函数(@Inject(PruebaServicio)prueba:PruebaType),但它不喜欢我,因为在这种情况下组件类必须具有对 PruebaServicio 的引用类,这是不正确的,我正在寻找打破与类的依赖关系并且只有接口的引用的方法。
标签: angular typescript