Manual injection in Dart

自闭症网瘾萝莉.ら 提交于 2019-12-11 02:45:21

问题


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


来源:https://stackoverflow.com/questions/20899346/manual-injection-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!