How does AngularDart dependency injection work?

2019-05-13 19:55发布

问题:

I have an component that needs to access its root element from the Dart code. By reading Differences between Angular.js and Angular.dart? here on SO and grepping around in the AngularDart source code I figured out that what I need is to provide a constructor with explicitly typed arguments. If one of the arguments has type dom.Element, it will be given the reference to my components root by the Angular injector. (Failing to have types on the constructor arguments results in an exception NoSuchMethodError : method not found: 'simpleName' being thrown from deep down in Angular internals.) My code now looks like this:

@ng.NgComponent (
    selector: 'math',
    templateUrl: 'packages/embarassing_name_of_my_package/math/math_component.html',
    publishAs: 'ctrl'
)
class MathComponent {
  ng.Scope _scope;
  dom.Element _element;
  ng.NgModel _ngModel;
  ng.NodeAttrs _attrs;

  MathComponent(this._scope, this._element, this._ngModel, this._attrs);

  …
}

with ng and dom being

import 'package:angular/angular.dart' as ng;
import 'dart:html' as dom;

Now the question. How do I best discover those special types that the injector reacts to?

Additionally, I'd like to know: Is it documented somewhere? Where? If not, where in the AngularDart source is the injector being configured to behave like this?

回答1:

Classes are registered using the Module.type() method (or factory, value).

You can take a look at Angular.dart source - search for 'type(' like lib/core/module.dart

(Please ignore the results where type is not the function name)

When a constructor or a method called by Angular needs a parameter DI looks up its registered types/values/factories and uses a provided instance (value) or creates a new instance (type) or uses the result that a factory returns and injects it.