gpt4 book ai didi

AngularDart 依赖注入(inject)

转载 作者:行者123 更新时间:2023-12-03 02:56:37 24 4
gpt4 key购买 nike

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

主要 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。我没有看到注入(inject)是如何解决的。

提前致谢,

编辑:我正在寻找的是如何告诉编译器生成如下行:
new AppComponent(new MyRepositoryImpl);

并像消费它一样
class AppComponent{
final MyRepository _repo;

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

最佳答案

使用 [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 引用注入(inject)器:
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);
}

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com