feat(di): add support for optional dependencies
This commit is contained in:
@@ -5,7 +5,7 @@ import {ProtoElementInjector, PreBuiltObjects, DirectiveBinding} from 'angular2/
|
||||
import {Parent, Ancestor} from 'angular2/src/core/annotations/visibility';
|
||||
import {EventEmitter} from 'angular2/src/core/annotations/events';
|
||||
import {onDestroy} from 'angular2/src/core/annotations/annotations';
|
||||
import {Injector, Inject, bind} from 'angular2/di';
|
||||
import {Optional, Injector, Inject, bind} from 'angular2/di';
|
||||
import {View} from 'angular2/src/core/compiler/view';
|
||||
import {ViewContainer} from 'angular2/src/core/compiler/view_container';
|
||||
import {NgElement} from 'angular2/src/core/dom/element';
|
||||
@@ -36,6 +36,13 @@ class NeedsDirective {
|
||||
}
|
||||
}
|
||||
|
||||
class OptionallyNeedsDirective {
|
||||
dependency:SimpleDirective;
|
||||
constructor(@Optional() dependency:SimpleDirective){
|
||||
this.dependency = dependency;
|
||||
}
|
||||
}
|
||||
|
||||
class NeedDirectiveFromParent {
|
||||
dependency:SimpleDirective;
|
||||
constructor(@Parent() dependency:SimpleDirective){
|
||||
@@ -342,6 +349,12 @@ export function main() {
|
||||
toThrowError('No provider for SimpleDirective! (NeedDirectiveFromParent -> SimpleDirective)');
|
||||
});
|
||||
|
||||
it("should inject null when no directive found", function () {
|
||||
var inj = injector([OptionallyNeedsDirective]);
|
||||
var d = inj.get(OptionallyNeedsDirective);
|
||||
expect(d.dependency).toEqual(null);
|
||||
});
|
||||
|
||||
it("should accept SimpleDirective bindings instead of SimpleDirective types", function () {
|
||||
var inj = injector([
|
||||
DirectiveBinding.createFromBinding(bind(SimpleDirective).toClass(SimpleDirective), null)
|
||||
|
||||
+17
-1
@@ -1,5 +1,5 @@
|
||||
import {describe, ddescribe, it, iit, expect, beforeEach} from 'angular2/test_lib';
|
||||
import {Injector, Inject, InjectLazy, bind} from 'angular2/di';
|
||||
import {Injector, Inject, InjectLazy, Optional, bind} from 'angular2/di';
|
||||
|
||||
class Engine {
|
||||
}
|
||||
@@ -34,6 +34,13 @@ class CarWithLazyEngine {
|
||||
}
|
||||
}
|
||||
|
||||
class CarWithOptionalEngine {
|
||||
engine;
|
||||
constructor(@Optional() engine:Engine) {
|
||||
this.engine = engine;
|
||||
}
|
||||
}
|
||||
|
||||
class CarWithDashboard {
|
||||
engine:Engine;
|
||||
dashboard:Dashboard;
|
||||
@@ -159,6 +166,15 @@ export function main() {
|
||||
expect(car.engine).toBeAnInstanceOf(Engine);
|
||||
});
|
||||
|
||||
it('should support optional dependencies', function () {
|
||||
var injector = new Injector([
|
||||
CarWithOptionalEngine
|
||||
]);
|
||||
|
||||
var car = injector.get(CarWithOptionalEngine);
|
||||
expect(car.engine).toEqual(null);
|
||||
});
|
||||
|
||||
it("should flatten passed-in bindings", function () {
|
||||
var injector = new Injector([
|
||||
[[Engine, Car]]
|
||||
|
||||
Reference in New Issue
Block a user