Benjamin Jesuiter
Benjamin Jesuiter

Reputation: 1162

How to use a Provider with 'useValue' in angular dart 2

I need to add an 'external' object to dependency injection in angular 2 for dart. 'External' means, it has no @Injectable annotation on it's constructor, because it's from an external library.

So i thought, i can add this dependency to angular 2 providers list in @Component annotation like this:

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

The Problem is that this list has to be a const expression. Therefore the Provider has to be const and `new EventBus()' is not supported through being a non-const expression.

Searching the docs didn't yield a result. How am I supposed to do this?

Upvotes: 1

Views: 781

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657218

You can register such classes in pubspec.yaml in the Angular2 transformer section:

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'

Above example shows how to make BrowserClient and BaseClient from the http package available to Angulars DI

You can then provide it like

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

or

eventBusFactory() => new EventBus();

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

Upvotes: 1

Related Questions