Manual injection in Dart

2019-07-17 02:49发布

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");

3条回答
Animai°情兽
2楼-- · 2019-07-17 03:26

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

查看更多
你好瞎i
3楼-- · 2019-07-17 03:26

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);
}
查看更多
在下西门庆
4楼-- · 2019-07-17 03:34

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;
    });    
  }
}
查看更多
登录 后发表回答