【问题标题】:How to use polymorphism with TypeScript, Interfaces and Dependency Injections in an Angular Project如何在 Angular 项目中使用 TypeScript、接口和依赖注入的多态性
【发布时间】: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


【解决方案1】:

我认为你需要创建一个抽象类:

接口 PruebaType

export interface PruebaType{
    calcularNombre(): string;
}

抽象 PruebaTypeService :

export abstract class PruebaTypeService implements PruebaType{

    abstract calcularNombre(): string;

}

您的服务

@Injectable()
export class PruebaServicio extends PruebaTypeService {
    calcularNombre(): string{
        return "Andy";
    }
}

现在你可以定义你的提供者了:

@NgModule({
      ...
      providers: [
        ...,
        {provide: PruebaTypeService , useClass: PruebaServicio }
      ]
})

【讨论】:

  • 嗨 Miguel,使用抽象类是个好主意,但实际上我正在使用接口进行搜索.... Miguel 现在我看到你的代码我产生了疑问,使用接口,我应该将接口引用添加到 app.modules.ts。文件?,我只添加了类引用,这种方式:@NgModule({...providers: [PruebaServicio]})。
  • 嗨@J.Abel,尝试使用{provide:PruebaType,useClass:PruebaServicio}初始化提供者。我不知道这是否有效。
  • 嗨米格尔。我尝试使用接口用户 {provide: PruebaType, useClass: PruebaServicio } 但它不起作用,它只适用于抽象类。
  • 如果PruebaServicio 类需要注入外部服务怎么办?
猜你喜欢
  • 2017-01-15
  • 1970-01-01
  • 2015-05-27
  • 2012-03-15
  • 2022-10-09
  • 2015-08-28
  • 2016-07-19
  • 2015-08-18
  • 2021-02-22
相关资源
最近更新 更多