From a82e20889d36a4c93abff1da8995486501810c44 Mon Sep 17 00:00:00 2001 From: Victor Berchet Date: Wed, 11 Mar 2015 15:14:16 +0100 Subject: [PATCH] feat(Injector): Support binding to null --- modules/angular2/src/di/injector.js | 14 +++++++------- modules/angular2/test/di/injector_spec.js | 5 +++++ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/modules/angular2/src/di/injector.js b/modules/angular2/src/di/injector.js index 4d62203ea0..3807abfabe 100644 --- a/modules/angular2/src/di/injector.js +++ b/modules/angular2/src/di/injector.js @@ -7,6 +7,7 @@ import {Promise, PromiseWrapper} from 'angular2/src/facade/async'; import {Key} from './key'; var _constructing = new Object(); +var _notFound = new Object(); class _Waiting { promise:Promise; @@ -72,10 +73,10 @@ export class Injector { var strategy = returnPromise ? this._asyncStrategy : this._syncStrategy; var instance = strategy.readFromCache(key); - if (isPresent(instance)) return instance; + if (instance !== _notFound) return instance; instance = strategy.instantiate(key); - if (isPresent(instance)) return instance; + if (instance !== _notFound) return instance; if (isPresent(this._parent)) { return this._parent._getByKey(key, returnPromise, returnLazy, optional); @@ -148,13 +149,13 @@ class _SyncInjectorStrategy { } else if (isPresent(instance) && !_isWaiting(instance)) { return instance; } else { - return null; + return _notFound; } } instantiate(key:Key) { var binding = this.injector._getBinding(key); - if (isBlank(binding)) return null; + if (isBlank(binding)) return _notFound; if (binding.providedAsPromise) throw new AsyncBindingError(key); @@ -198,13 +199,13 @@ class _AsyncInjectorStrategy { } else if (isPresent(instance)) { return PromiseWrapper.resolve(instance); } else { - return null; + return _notFound; } } instantiate(key:Key) { var binding = this.injector._getBinding(key); - if (isBlank(binding)) return null; + if (isBlank(binding)) return _notFound; //add a marker so we can detect cyclic dependencies this.injector._markAsConstructing(key); @@ -243,7 +244,6 @@ class _AsyncInjectorStrategy { } } - function _flattenBindings(bindings:List, res:Map) { ListWrapper.forEach(bindings, function (b) { if (b instanceof Binding) { diff --git a/modules/angular2/test/di/injector_spec.js b/modules/angular2/test/di/injector_spec.js index 404a338d76..e030a60da6 100644 --- a/modules/angular2/test/di/injector_spec.js +++ b/modules/angular2/test/di/injector_spec.js @@ -267,6 +267,11 @@ export function main() { expect(injector.get(Car)).toBeAnInstanceOf(Car); }); + it('should support null values', () => { + var injector = new Injector([bind('null').toValue(null)]); + expect(injector.get('null')).toBe(null); + }); + describe("default bindings", function () { it("should be used when no matching binding found", function () { var injector = new Injector([], {defaultBindings: true});