【问题标题】:How to use a Provider with 'useValue' in angular dart 2如何在 angular dart 2 中使用带有“useValue”的提供者
【发布时间】:2017-02-10 14:39:04
【问题描述】:

我需要在 Angular 2 中为 dart 添加一个“外部”对象到依赖注入。 “外部”的意思是,它的构造函数上没有 @Injectable 注释,因为它来自外部库。

所以我想,我可以像这样在@Component 注释中将此依赖项添加到 Angular 2 提供程序列表中:

@Component(
    selector: "app-component",
    templateUrl: "app_component.html",
    directives: const [AddButton, SettingsButton],
    providers: const [const Provider(EventBus, useValue: new EventBus())]
)

问题是这个列表必须是一个 const 表达式。因此 Provider 必须是 const 并且 `new EventBus()' 不被支持为非常量表达式。

搜索文档没有产生结果。 我该怎么做?

【问题讨论】:

    标签: angular dart


    【解决方案1】:

    您可以在 Angular2 转换器部分的 pubspec.yaml 中注册此类:

    transformers:
    - sass
    - angular2:
        platform_directives:
        - 'package:angular2/common.dart#COMMON_DIRECTIVES'
        platform_pipes:
        - 'package:angular2/common.dart#COMMON_PIPES'
        entry_points:
        - web/index.dart
        resolved_identifiers:
            BrowserClient: 'package:http/browser_client.dart'
            BaseClient: 'package:http/http.dart'
    

    上面的例子展示了如何将http包中的BrowserClient和BaseClient提供给Angulars DI

    然后你可以像这样提供它

    罢工>

    @Component(
        selector: "app-component",
        templateUrl: "app_component.html",
        directives: const [AddButton, SettingsButton],
        providers: const [EventBus]
    )
    

    或

    eventBusFactory() => new EventBus();
    
    @Component(
        selector: "app-component",
        templateUrl: "app_component.html",
        directives: const [AddButton, SettingsButton],
        providers: const [const Provider(EventBus, useFactory: eventBusFactory)]
    )
    

    【讨论】:

    • 啊,好吧:DI 意识到第二部分是在您编辑帖子时及时为自己提供价值:D - 但是“useValue”仍然不起作用,因为 Dart Analyzer 抱怨非常量值在常量列表中。但至少工厂方式是有效的。工厂的一个附带问题:Angular 会在每次注入时在工厂的帮助下创造一个新价值,还是会一次创造价值并在每次注入时提供该单一价值?
    • 对不起,我忘记编辑第一部分。我更新了答案。我认为它也应该以这种方式工作(虽然未经测试)。
    • 不,当我用简单的const [EventBus] 测试它时,它稍后会在 chrome 开发工具中抱怨,找不到 EventBus 的提供程序。所以它现在唯一可行的方法是使用工厂。
    • 此类课程我只使用了useFactory。
    • 啊,好吧!感谢您的帮助! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2015-07-26
    • 2018-01-09
    相关资源
    最近更新 更多