dart - 接口(interface)的依赖注入(inject)

标签 dart angular-dart

我有一个包含通用弹出窗口的组件,因此它实现了接口(interface)PopupParent

@Injectable()
@Component(
    //...
)
class SubjectListComponent implements OnInit, PopupParent {
}

泛型类InfoPopup需要抽象地处理它的父类(实现PopupParent),所以我想获取通过其接口(interface)注入(inject)的父类(而不是由其具体类 SubjectListComponent 注入(inject))

class InfoPopup {
  final PopupParent _parent;

  InfoPopup(this._parent);
  //...non relevant code
}

问题在于 SubjectListComponent 是按注入(inject)器中的类注册的,因此注入(inject)器找不到要注入(inject)到 InfoPopup 类中的内容。

如果我尝试手动声明我的SubjectListComponent,我发现它必须在提供程序常量中完成。但当我声明我的组件时,我仍然没有 SubjectListComponent 实例...

我怎样才能做到这一点?

我还尝试将父级传递给@Input:

@Component(
    selector: 'info-popup',
    templateUrl: 'info_popup.html',
    styleUrls: const ['info_popup.css'],
)
class InfoPopup {
  @Input()
  final PopupParent parent;

  InfoPopup(this._parent);
  //...non relevant code
}

但是后来我陷入了如何从组件客户端注入(inject) this 实例的困境:

subject_list_comp.html:

<div>
  <info-popup [parent]="this"></info-popup>
</div>

因为 dart Angular 无法将 this 识别为关键字,但它会在 subjectListComponent.dart 中搜索名为 this 的属性

针对此问题创建了两个问题: https://github.com/dart-lang/site-webdev/issues/514 https://github.com/dart-lang/site-webdev/issues/515

最佳答案

这可以通过提供别名来完成。 multi: true 允许添加多个别名。没有办法自动派生接口(interface)。

@Component(
  providers: [
      const Provider(PopupParent, useExisting: SubjectListComponent, multi: true),
      const Provider(PopupParent, useExisting: FooComponent, multi: true)

  ]
)
class InfoPoupup ...

更新

制作

[parent]="this" 

工作,你可以向组件添加一个 setter/getter

get self => this; 

然后使用

[parent]="self"

关于dart - 接口(interface)的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43185353/

相关文章:

dart - 我可以从Angular.Dart收回对URL哈希片段的控制吗?

json - 类型错误问题将对象列表从 Json 转换为类结构

android-studio - Android Studio IDE : how to debug through my code only in Flutter?

flutter - 如何使用 ContinuousRectangleBorder 的 getOuterPath 使其看起来像倒圆形边框?

dart - 自定义Angular Dart组件包

dart - 在 Angular 2 中编写可扩展组件

html - 在 AngularDart 中的 Material 选项卡之间切换会破坏子元素

firebase - 有没有一种简单的方法可以找到在 flutter 中使用权限的包? Info.plist 提交问题中缺少目的字符串

flutter - 获取 token 失败

css - 在浏览器调整大小之前,AngularDart NgComponent 不存在