Manual injection in Dart

2019-07-17 03:42发布

问题:

How do you manually inject an instance in angular dart? This would be the equivalent to the following in angularjs:

var myInjector = angular.injector(["ng"]);
var $http = myInjector.get("$http");

回答1:

A code example from inside a component.

@NgComponent(
    selector: 'rating',
    publishAs: 'ctrl')
class RatingComponent {
  Injector _injector;
  RatingConfig _config;

  RatingComponent(this._injector) {
    _config = _injector.get(RatingConfig);
    // or
    _config = injectByName("RatingConfig");
  }

  void injectByName(String typeName) {
    _injector.types.takeWhile((Type e) {
      if (e.toString() == typeName) {
        _config = _injector.get(e);
        return false;
      }
      return true;
    });    
  }
}


回答2:

The approach of using _injector.get(RatingConfig) will work.

As an example, the filter code calls 'get' explicitly on the injector to get an instance of a filter: lib/core/filter.dart, line 50



回答3:

If you need to manually inject an instance because your are in the main() method, you can do the following:

class MyAppModule extends Module {
  MyAppModule() {
    type(MyService);
  }
}

main() {
  Injector injector = applicationFactory().addModule(new MyAppModule()).run();
  MyService myService = injector.get(MyService);
}