AngularDart依赖注入

时间:2019-02-15 06:47:54

标签: angular dependency-injection dart angular-dart

我正在使用AngularDart,我不知道如何注入我的入口点依赖项。

Main.dart:

import 'package:angular/angular.dart';
import 'package:angular_dart/app_component.dart';
import 'package:angular_dart/app_component.template.dart' as ng;

@GenerateInjector(const [
  const Provider(MyRepository, useClass: ng.MyRepositoryImpl),
])
final InjectorFactory appInjector = ng.appInjector$Injector;

void main() {
  runApp(ng.AppComponentNgFactory, createInjector: appInjector);
}

app_component.dart

import 'package:angular/angular.dart';

@Component(
  selector: 'app-component',
  templateUrl: 'app_component.html',
  providers: [ClassProvider(MyRepository)]
)
class AppComponent {
  MyRepository myRepository; //This is not getting injected
}

abstract class MyRepository {
}

class MyRepositoryImpl implements MyRepository {
}

我的问题是关于runApp方法和ng.AppComponentNgFactory的。我看不到如何解决注射问题。

预先感谢

编辑:我要寻找的是如何告诉编译器生成如下行:

new AppComponent(new MyRepositoryImpl);

像这样食用

class AppComponent{
final MyRepository _repo;

AppComponent(MyRepository repo) {
this._repo = repo;
}
}

1 个答案:

答案 0 :(得分:2)

[ClassProvider(MyRepository)]中使用app_component告诉编译器覆盖main.dart文件中设置的内容。

尝试一下:

@Component(
  selector: 'app-component',
  templateUrl: 'app_component.html',
)
@Injectable()
class AppComponent {
  final MyRepository _myRepository;

  AppComponent(this._myRepository);
}

编辑:

您的main.dart文件不正确,您必须从main.template.dart引用注入器:

import 'package:angular/angular.dart';
import 'package:angular_dart/app_component.dart';
import 'package:angular_dart/app_component.template.dart' as ng;
import 'main.template.dart' as self;

@GenerateInjector([
  ClassProvider(MyRepository, useClass: ng.MyRepositoryImpl),
])
final InjectorFactory injector = self.injector$Injector;

void main() {
  runApp(ng.AppComponentNgFactory, createInjector: injector);
}
相关问题