feat(di): rename Binding into Provider

Closes #4416

Closes #4654
This commit is contained in:
vsavkin 2015-10-10 22:11:13 -07:00 committed by Victor Savkin
parent 7c6130c2c5
commit 1eb0162cde
190 changed files with 2071 additions and 1816 deletions

View File

@ -72,7 +72,7 @@ module.exports = new Package('angular-v2-docs', [jsdocPackage, nunjucksPackage,
{
id: 'angular2/test_lib',
references: ['./angular2.d.ts'],
remapTypes: { Type: 'ng.Type', Binding: 'ng.Binding', ViewMetadata: 'ng.ViewMetadata', Injector: 'ng.Injector',
remapTypes: { Type: 'ng.Type', Binding: 'ng.Binding', Provider: 'ng.Provider', ViewMetadata: 'ng.ViewMetadata', Injector: 'ng.Injector',
Predicate: 'ng.Predicate', ElementRef: 'ng.ElementRef', DebugElement: 'ng.DebugElement',
InjectableReference: 'ng.InjectableReference', ComponentRef: 'ng.ComponentRef' },
modules: {'angular2/test_lib': {namespace: 'ngTestLib', id: 'angular2/test_lib'}}

View File

@ -8,5 +8,5 @@ library angular2;
export 'package:angular2/core.dart' hide forwardRef, resolveForwardRef, ForwardRefFn;
export 'package:angular2/profile.dart';
export 'package:angular2/lifecycle_hooks.dart';
export 'package:angular2/src/core/application_tokens.dart' hide APP_COMPONENT_REF_PROMISE, APP_ID_RANDOM_BINDING;
export 'package:angular2/src/core/application_tokens.dart' hide APP_COMPONENT_REF_PROMISE, APP_ID_RANDOM_PROVIDER;
export 'package:angular2/src/core/render/dom/dom_tokens.dart';

View File

@ -108,7 +108,7 @@ while (inj) {
inj = inj.parent;
}
}
throw new NoBindingError(requestedKey);
throw new NoProviderError(requestedKey);
```
So in the following example
@ -160,7 +160,7 @@ var child = parent.resolveAndCreateChild([
bind(Engine).toClass(TurboEngine)
]);
parent.get(Car); // will throw NoBindingError
parent.get(Car); // will throw NoProviderError
```

View File

@ -4,7 +4,7 @@
* The http module provides services to perform http requests. To get started, see the {@link Http}
* class.
*/
import {bind, Binding} from 'angular2/core';
import {provide, Provider} from 'angular2/core';
import {Http, Jsonp} from './src/http/http';
import {XHRBackend, XHRConnection} from './src/http/backends/xhr_backend';
import {JSONPBackend, JSONPBackend_, JSONPConnection} from './src/http/backends/jsonp_backend';
@ -40,18 +40,18 @@ export {URLSearchParams} from './src/http/url_search_params';
/**
* Provides a basic set of injectables to use the {@link Http} service in any application.
*
* The `HTTP_BINDINGS` should be included either in a component's injector,
* The `HTTP_PROVIDERS` should be included either in a component's injector,
* or in the root injector when bootstrapping an application.
*
* ### Example ([live demo](http://plnkr.co/edit/snj7Nv?p=preview))
*
* ```
* import {bootstrap, Component, NgFor, View} from 'angular2/angular2';
* import {HTTP_BINDINGS, Http} from 'angular2/http';
* import {HTTP_PROVIDERS, Http} from 'angular2/http';
*
* @Component({
* selector: 'app',
* bindings: [HTTP_BINDINGS]
* providers: [HTTP_PROVIDERS]
* })
* @View({
* template: `
@ -83,11 +83,11 @@ export {URLSearchParams} from './src/http/url_search_params';
* .catch(err => console.error(err));
* ```
*
* The primary public API included in `HTTP_BINDINGS` is the {@link Http} class.
* However, other bindings required by `Http` are included,
* The primary public API included in `HTTP_PROVIDERS` is the {@link Http} class.
* However, other providers required by `Http` are included,
* which may be beneficial to override in certain cases.
*
* The bindings included in `HTTP_BINDINGS` include:
* The providers included in `HTTP_PROVIDERS` include:
* * {@link Http}
* * {@link XHRBackend}
* * `BrowserXHR` - Private factory to create `XMLHttpRequest` instances
@ -96,38 +96,38 @@ export {URLSearchParams} from './src/http/url_search_params';
*
* There may be cases where it makes sense to extend the base request options,
* such as to add a search string to be appended to all URLs.
* To accomplish this, a new binding for {@link RequestOptions} should
* be added in the same injector as `HTTP_BINDINGS`.
* To accomplish this, a new provider for {@link RequestOptions} should
* be added in the same injector as `HTTP_PROVIDERS`.
*
* ### Example ([live demo](http://plnkr.co/edit/aCMEXi?p=preview))
*
* ```
* import {bind, bootstrap} from 'angular2/angular2';
* import {HTTP_BINDINGS, BaseRequestOptions, RequestOptions} from 'angular2/http';
* import {provide, bootstrap} from 'angular2/angular2';
* import {HTTP_PROVIDERS, BaseRequestOptions, RequestOptions} from 'angular2/http';
*
* class MyOptions extends BaseRequestOptions {
* search: string = 'coreTeam=true';
* }
*
* bootstrap(App, [HTTP_BINDINGS, bind(RequestOptions).toClass(MyOptions)])
* bootstrap(App, [HTTP_PROVIDERS, provide(RequestOptions, {asClass: MyOptions})])
* .catch(err => console.error(err));
* ```
*
* Likewise, to use a mock backend for unit tests, the {@link XHRBackend}
* binding should be bound to {@link MockBackend}.
* provider should be bound to {@link MockBackend}.
*
* ### Example ([live demo](http://plnkr.co/edit/7LWALD?p=preview))
*
* ```
* import {bind, Injector} from 'angular2/angular2';
* import {HTTP_BINDINGS, Http, Response, XHRBackend, MockBackend} from 'angular2/http';
* import {provide, Injector} from 'angular2/angular2';
* import {HTTP_PROVIDERS, Http, Response, XHRBackend, MockBackend} from 'angular2/http';
*
* var people = [{name: 'Jeff'}, {name: 'Tobias'}];
*
* var injector = Injector.resolveAndCreate([
* HTTP_BINDINGS,
* HTTP_PROVIDERS,
* MockBackend,
* bind(XHRBackend).toAlias(MockBackend)
* provide(XHRBackend, {asAlias: MockBackend})
* ]);
* var http = injector.get(Http);
* var backend = injector.get(MockBackend);
@ -150,34 +150,40 @@ export {URLSearchParams} from './src/http/url_search_params';
* });
* ```
*/
export const HTTP_BINDINGS: any[] = [
export const HTTP_PROVIDERS: any[] = [
// TODO(pascal): use factory type annotations once supported in DI
// issue: https://github.com/angular/angular/issues/3183
bind(Http)
.toFactory((xhrBackend, requestOptions) => { return new Http(xhrBackend, requestOptions);},
[XHRBackend, RequestOptions]),
provide(Http,
{
asFactory: (xhrBackend, requestOptions) => new Http(xhrBackend, requestOptions),
deps: [XHRBackend, RequestOptions]
}),
BrowserXhr,
bind(RequestOptions).toClass(BaseRequestOptions),
bind(ResponseOptions).toClass(BaseResponseOptions),
provide(RequestOptions, {asClass: BaseRequestOptions}),
provide(ResponseOptions, {asClass: BaseResponseOptions}),
XHRBackend
];
/**
* @deprecated
*/
export const HTTP_BINDINGS = HTTP_PROVIDERS;
/**
* Provides a basic set of bindings to use the {@link Jsonp} service in any application.
* Provides a basic set of providers to use the {@link Jsonp} service in any application.
*
* The `JSONP_BINDINGS` should be included either in a component's injector,
* The `JSONP_PROVIDERS` should be included either in a component's injector,
* or in the root injector when bootstrapping an application.
*
* ### Example ([live demo](http://plnkr.co/edit/vmeN4F?p=preview))
*
* ```
* import {Component, NgFor, View} from 'angular2/angular2';
* import {JSONP_BINDINGS, Jsonp} from 'angular2/http';
* import {JSONP_PROVIDERS, Jsonp} from 'angular2/http';
*
* @Component({
* selector: 'app',
* bindings: [JSONP_BINDINGS]
* providers: [JSONP_PROVIDERS]
* })
* @View({
* template: `
@ -202,11 +208,11 @@ export const HTTP_BINDINGS: any[] = [
* }
* ```
*
* The primary public API included in `JSONP_BINDINGS` is the {@link Jsonp} class.
* However, other bindings required by `Jsonp` are included,
* The primary public API included in `JSONP_PROVIDERS` is the {@link Jsonp} class.
* However, other providers required by `Jsonp` are included,
* which may be beneficial to override in certain cases.
*
* The bindings included in `JSONP_BINDINGS` include:
* The providers included in `JSONP_PROVIDERS` include:
* * {@link Jsonp}
* * {@link JSONPBackend}
* * `BrowserJsonp` - Private factory
@ -215,37 +221,37 @@ export const HTTP_BINDINGS: any[] = [
*
* There may be cases where it makes sense to extend the base request options,
* such as to add a search string to be appended to all URLs.
* To accomplish this, a new binding for {@link RequestOptions} should
* be added in the same injector as `JSONP_BINDINGS`.
* To accomplish this, a new provider for {@link RequestOptions} should
* be added in the same injector as `JSONP_PROVIDERS`.
*
* ### Example ([live demo](http://plnkr.co/edit/TFug7x?p=preview))
*
* ```
* import {bind, bootstrap} from 'angular2/angular2';
* import {JSONP_BINDINGS, BaseRequestOptions, RequestOptions} from 'angular2/http';
* import {provide, bootstrap} from 'angular2/angular2';
* import {JSONP_PROVIDERS, BaseRequestOptions, RequestOptions} from 'angular2/http';
*
* class MyOptions extends BaseRequestOptions {
* search: string = 'coreTeam=true';
* }
*
* bootstrap(App, [JSONP_BINDINGS, bind(RequestOptions).toClass(MyOptions)])
* bootstrap(App, [JSONP_PROVIDERS, provide(RequestOptions, {asClass: MyOptions})])
* .catch(err => console.error(err));
* ```
*
* Likewise, to use a mock backend for unit tests, the {@link JSONPBackend}
* binding should be bound to {@link MockBackend}.
* provider should be bound to {@link MockBackend}.
*
* ### Example ([live demo](http://plnkr.co/edit/HDqZWL?p=preview))
*
* ```
* import {bind, Injector} from 'angular2/angular2';
* import {JSONP_BINDINGS, Jsonp, Response, JSONPBackend, MockBackend} from 'angular2/http';
* import {provide, Injector} from 'angular2/angular2';
* import {JSONP_PROVIDERS, Jsonp, Response, JSONPBackend, MockBackend} from 'angular2/http';
*
* var people = [{name: 'Jeff'}, {name: 'Tobias'}];
* var injector = Injector.resolveAndCreate([
* JSONP_BINDINGS,
* JSONP_PROVIDERS,
* MockBackend,
* bind(JSONPBackend).toAlias(MockBackend)
* provide(JSONPBackend, {asAlias: MockBackend})
* ]);
* var jsonp = injector.get(Jsonp);
* var backend = injector.get(MockBackend);
@ -268,15 +274,21 @@ export const HTTP_BINDINGS: any[] = [
* });
* ```
*/
export const JSONP_BINDINGS: any[] = [
export const JSONP_PROVIDERS: any[] = [
// TODO(pascal): use factory type annotations once supported in DI
// issue: https://github.com/angular/angular/issues/3183
bind(Jsonp)
.toFactory(
(jsonpBackend, requestOptions) => { return new Jsonp(jsonpBackend, requestOptions);},
[JSONPBackend, RequestOptions]),
provide(Jsonp,
{
asFactory: (jsonpBackend, requestOptions) => new Jsonp(jsonpBackend, requestOptions),
deps: [JSONPBackend, RequestOptions]
}),
BrowserJsonp,
bind(RequestOptions).toClass(BaseRequestOptions),
bind(ResponseOptions).toClass(BaseResponseOptions),
bind(JSONPBackend).toClass(JSONPBackend_)
provide(RequestOptions, {asClass: BaseRequestOptions}),
provide(ResponseOptions, {asClass: BaseResponseOptions}),
provide(JSONPBackend, {asClass: JSONPBackend_})
];
/**
* @deprecated
*/
export const JSON_BINDINGS = JSONP_PROVIDERS;

View File

@ -28,7 +28,7 @@ import {RouterOutlet} from './src/router/router_outlet';
import {RouterLink} from './src/router/router_link';
import {RouteRegistry} from './src/router/route_registry';
import {Location} from './src/router/location';
import {bind, OpaqueToken, Binding} from './core';
import {provide, OpaqueToken, Provider} from './core';
import {CONST_EXPR} from './src/core/facade/lang';
import {ApplicationRef} from './src/core/application_ref';
import {BaseException} from 'angular2/src/core/facade/exceptions';
@ -44,7 +44,7 @@ import {BaseException} from 'angular2/src/core/facade/exceptions';
* import {Component, View} from 'angular2/angular2';
* import {
* ROUTER_DIRECTIVES,
* ROUTER_BINDINGS,
* ROUTER_PROVIDERS,
* RouteConfig
* } from 'angular2/router';
*
@ -57,7 +57,7 @@ import {BaseException} from 'angular2/src/core/facade/exceptions';
* // ...
* }
*
* bootstrap(AppCmp, [ROUTER_BINDINGS]);
* bootstrap(AppCmp, [ROUTER_PROVIDERS]);
* ```
*/
export const ROUTER_PRIMARY_COMPONENT: OpaqueToken =
@ -72,7 +72,7 @@ export const ROUTER_PRIMARY_COMPONENT: OpaqueToken =
*
* ```
* import {Component, View} from 'angular2/angular2';
* import {ROUTER_DIRECTIVES, ROUTER_BINDINGS, RouteConfig} from 'angular2/router';
* import {ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig} from 'angular2/router';
*
* @Component({...})
* @View({directives: [ROUTER_DIRECTIVES]})
@ -83,13 +83,13 @@ export const ROUTER_PRIMARY_COMPONENT: OpaqueToken =
* // ...
* }
*
* bootstrap(AppCmp, ROUTER_BINDINGS);
* bootstrap(AppCmp, [ROUTER_PROVIDERS]);
* ```
*/
export const ROUTER_DIRECTIVES: any[] = CONST_EXPR([RouterOutlet, RouterLink]);
/**
* A list of {@link Binding}s. To use the router, you must add this to your application.
* A list of {@link Provider}s. To use the router, you must add this to your application.
*
* ## Example ([live demo](http://plnkr.co/edit/iRUP8B5OUbxCWQ3AcIDm))
*
@ -97,7 +97,7 @@ export const ROUTER_DIRECTIVES: any[] = CONST_EXPR([RouterOutlet, RouterLink]);
* import {Component, View} from 'angular2/angular2';
* import {
* ROUTER_DIRECTIVES,
* ROUTER_BINDINGS,
* ROUTER_PROVIDERS,
* RouteConfig
* } from 'angular2/router';
*
@ -110,23 +110,29 @@ export const ROUTER_DIRECTIVES: any[] = CONST_EXPR([RouterOutlet, RouterLink]);
* // ...
* }
*
* bootstrap(AppCmp, [ROUTER_BINDINGS]);
* bootstrap(AppCmp, [ROUTER_PROVIDERS]);
* ```
*/
export const ROUTER_BINDINGS: any[] = CONST_EXPR([
export const ROUTER_PROVIDERS: any[] = CONST_EXPR([
RouteRegistry,
CONST_EXPR(new Binding(LocationStrategy, {toClass: PathLocationStrategy})),
CONST_EXPR(new Provider(LocationStrategy, {toClass: PathLocationStrategy})),
Location,
CONST_EXPR(new Binding(Router,
{
toFactory: routerFactory,
deps: CONST_EXPR([RouteRegistry, Location, ROUTER_PRIMARY_COMPONENT])
})),
CONST_EXPR(new Binding(
CONST_EXPR(
new Provider(Router,
{
toFactory: routerFactory,
deps: CONST_EXPR([RouteRegistry, Location, ROUTER_PRIMARY_COMPONENT])
})),
CONST_EXPR(new Provider(
ROUTER_PRIMARY_COMPONENT,
{toFactory: routerPrimaryComponentFactory, deps: CONST_EXPR([ApplicationRef])}))
]);
/**
* @deprecated
*/
export const ROUTER_BINDINGS = ROUTER_PROVIDERS;
function routerFactory(registry, location, primaryComponent) {
return new RootRouter(registry, location, primaryComponent);
}

View File

@ -18,11 +18,11 @@ export 'package:angular2/src/core/linker/dynamic_component_loader.dart' show Com
///
/// See [commonBootstrap] for detailed documentation.
Future<ComponentRef> bootstrap(Type appComponentType,
[List componentInjectableBindings]) {
[List componentInjectableProviders]) {
reflector.reflectionCapabilities = new ReflectionCapabilities();
var bindings = [compilerBindings()];
if (componentInjectableBindings != null) {
bindings.add(componentInjectableBindings);
var providers = [compilerProviders()];
if (componentInjectableProviders != null) {
providers.add(componentInjectableProviders);
}
return commonBootstrap(appComponentType, bindings);
return commonBootstrap(appComponentType, providers);
}

View File

@ -1,8 +1,8 @@
// Public API for Application
import {Binding} from './di';
import {Provider} from './di';
import {Type, isPresent} from 'angular2/src/core/facade/lang';
import {Promise} from 'angular2/src/core/facade/async';
import {compilerBindings} from 'angular2/src/core/compiler/compiler';
import {compilerProviders} from 'angular2/src/core/compiler/compiler';
import {commonBootstrap} from './application_common';
import {ComponentRef} from './linker/dynamic_component_loader';
@ -19,9 +19,9 @@ export {
/// See [commonBootstrap] for detailed documentation.
export function bootstrap(appComponentType: /*Type*/ any,
appBindings: Array<Type | Binding | any[]> = null):
appBindings: Array<Type | Provider | any[]> = null):
Promise<ComponentRef> {
var bindings = [compilerBindings()];
var bindings = [compilerProviders()];
if (isPresent(appBindings)) {
bindings.push(appBindings);
}

View File

@ -1,5 +1,5 @@
import {FORM_BINDINGS} from 'angular2/src/core/forms';
import {bind, Binding, Injector, OpaqueToken} from 'angular2/src/core/di';
import {FORM_PROVIDERS} from 'angular2/src/core/forms';
import {provide, Provider, Injector, OpaqueToken} from 'angular2/src/core/di';
import {
NumberWrapper,
Type,
@ -34,37 +34,36 @@ import {
SharedStylesHost,
DomSharedStylesHost
} from 'angular2/src/core/render/dom/shared_styles_host';
import {EXCEPTION_BINDING} from './platform_bindings';
import {EXCEPTION_PROVIDER} from './platform_bindings';
import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
import {BrowserDetails} from 'angular2/src/animate/browser_details';
import {wtfInit} from './profile/wtf_init';
import {platformCommon, PlatformRef, applicationCommonBindings} from './application_ref';
/**
* A default set of bindings which apply only to an Angular application running on
* A default set of providers which apply only to an Angular application running on
* the UI thread.
*/
export function applicationDomBindings(): Array<Type | Binding | any[]> {
export function applicationDomBindings(): Array<Type | Provider | any[]> {
if (isBlank(DOM)) {
throw "Must set a root DOM adapter first.";
}
return [
bind(DOCUMENT)
.toValue(DOM.defaultDoc()),
provide(DOCUMENT, {asValue: DOM.defaultDoc()}),
EventManager,
new Binding(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true}),
new Binding(EVENT_MANAGER_PLUGINS, {toClass: KeyEventsPlugin, multi: true}),
new Binding(EVENT_MANAGER_PLUGINS, {toClass: HammerGesturesPlugin, multi: true}),
bind(DomRenderer).toClass(DomRenderer_),
bind(Renderer).toAlias(DomRenderer),
new Provider(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true}),
new Provider(EVENT_MANAGER_PLUGINS, {toClass: KeyEventsPlugin, multi: true}),
new Provider(EVENT_MANAGER_PLUGINS, {toClass: HammerGesturesPlugin, multi: true}),
provide(DomRenderer, {asClass: DomRenderer_}),
provide(Renderer, {asAlias: DomRenderer}),
DomSharedStylesHost,
bind(SharedStylesHost).toAlias(DomSharedStylesHost),
EXCEPTION_BINDING,
bind(XHR).toValue(new XHRImpl()),
provide(SharedStylesHost, {asAlias: DomSharedStylesHost}),
EXCEPTION_PROVIDER,
provide(XHR, {asValue: new XHRImpl()}),
Testability,
BrowserDetails,
AnimationBuilder,
FORM_BINDINGS
FORM_PROVIDERS
];
}
@ -73,25 +72,25 @@ export function applicationDomBindings(): Array<Type | Binding | any[]> {
*
* See {@link PlatformRef} for details on the Angular platform.
*
* # Without specified bindings
* # Without specified providers
*
* If no bindings are specified, `platform`'s behavior depends on whether an existing
* If no providers are specified, `platform`'s behavior depends on whether an existing
* platform exists:
*
* If no platform exists, a new one will be created with the default {@link platformBindings}.
*
* If a platform already exists, it will be returned (regardless of what bindings it
* If a platform already exists, it will be returned (regardless of what providers it
* was created with). This is a convenience feature, allowing for multiple applications
* to be loaded into the same platform without awareness of each other.
*
* # With specified bindings
* # With specified providers
*
* It is also possible to specify bindings to be made in the new platform. These bindings
* It is also possible to specify providers to be made in the new platform. These providers
* will be shared between all applications on the page. For example, an abstraction for
* the browser cookie jar should be bound at the platform level, because there is only one
* cookie jar regardless of how many applications on the age will be accessing it.
*
* If bindings are specified directly, `platform` will create the Angular platform with
* If providers are specified directly, `platform` will create the Angular platform with
* them if a platform did not exist already. If it did exist, however, an error will be
* thrown.
*
@ -101,7 +100,7 @@ export function applicationDomBindings(): Array<Type | Binding | any[]> {
* DOM access. Web-worker applications should call `platform` from
* `src/web_workers/worker/application_common` instead.
*/
export function platform(bindings?: Array<Type | Binding | any[]>): PlatformRef {
export function platform(bindings?: Array<Type | Provider | any[]>): PlatformRef {
return platformCommon(bindings, () => {
BrowserDomAdapter.makeCurrent();
wtfInit();
@ -129,10 +128,10 @@ export function platform(bindings?: Array<Type | Binding | any[]>): PlatformRef
* ```
*
* An application is bootstrapped inside an existing browser DOM, typically `index.html`.
* Unlike Angular 1, Angular 2 does not compile/process bindings in `index.html`. This is
* Unlike Angular 1, Angular 2 does not compile/process providers in `index.html`. This is
* mainly for security reasons, as well as architectural changes in Angular 2. This means
* that `index.html` can safely be processed using server-side technologies such as
* bindings. Bindings can thus use double-curly `{{ syntax }}` without collision from
* providers. Bindings can thus use double-curly `{{ syntax }}` without collision from
* Angular 2 component double-curly `{{ syntax }}`.
*
* We can use this script code:
@ -170,7 +169,7 @@ export function platform(bindings?: Array<Type | Binding | any[]>): PlatformRef
* 4. It creates a shadow DOM on the selected component's host element and loads the
* template into it.
* 5. It instantiates the specified component.
* 6. Finally, Angular performs change detection to apply the initial data bindings for the
* 6. Finally, Angular performs change detection to apply the initial data providers for the
* application.
*
*
@ -214,7 +213,7 @@ export function platform(bindings?: Array<Type | Binding | any[]>): PlatformRef
* # API
* - `appComponentType`: The root component which should act as the application. This is
* a reference to a `Type` which is annotated with `@Component(...)`.
* - `componentInjectableBindings`: An additional set of bindings that can be added to the
* - `componentInjectableBindings`: An additional set of providers that can be added to the
* app injector to override default injection behavior.
* - `errorReporter`: `function(exception:any, stackTrace:string)` a default error reporter
* for unhandled exceptions.
@ -222,7 +221,7 @@ export function platform(bindings?: Array<Type | Binding | any[]>): PlatformRef
* Returns a `Promise` of {@link ComponentRef}.
*/
export function commonBootstrap(appComponentType: /*Type*/ any,
appBindings: Array<Type | Binding | any[]> = null):
appBindings: Array<Type | Provider | any[]> = null):
Promise<ComponentRef> {
var p = platform();
var bindings = [applicationCommonBindings(), applicationDomBindings()];

View File

@ -1,10 +1,10 @@
import {NgZone} from 'angular2/src/core/zone/ng_zone';
import {Type, isBlank, isPresent, assertionsEnabled} from 'angular2/src/core/facade/lang';
import {bind, Binding, Injector, OpaqueToken} from 'angular2/src/core/di';
import {provide, Provider, Injector, OpaqueToken} from 'angular2/src/core/di';
import {
APP_COMPONENT_REF_PROMISE,
APP_COMPONENT,
APP_ID_RANDOM_BINDING
APP_ID_RANDOM_PROVIDER
} from './application_tokens';
import {Promise, PromiseWrapper, PromiseCompleter} from 'angular2/src/core/facade/async';
import {ListWrapper} from 'angular2/src/core/facade/collection';
@ -44,67 +44,71 @@ import {AppViewManager_} from "./linker/view_manager";
import {Compiler_} from "./linker/compiler";
/**
* Constructs the set of bindings meant for use at the platform level.
* Constructs the set of providers meant for use at the platform level.
*
* These are bindings that should be singletons shared among all Angular applications
* These are providers that should be singletons shared among all Angular applications
* running on the page.
*/
export function platformBindings(): Array<Type | Binding | any[]> {
return [bind(Reflector).toValue(reflector), TestabilityRegistry];
export function platformBindings(): Array<Type | Provider | any[]> {
return [provide(Reflector, {asValue: reflector}), TestabilityRegistry];
}
/**
* Construct bindings specific to an individual root component.
* Construct providers specific to an individual root component.
*/
function _componentBindings(appComponentType: Type): Array<Type | Binding | any[]> {
function _componentProviders(appComponentType: Type): Array<Type | Provider | any[]> {
return [
bind(APP_COMPONENT)
.toValue(appComponentType),
bind(APP_COMPONENT_REF_PROMISE)
.toFactory(
(dynamicComponentLoader, injector: Injector) => {
// TODO(rado): investigate whether to support bindings on root component.
return dynamicComponentLoader.loadAsRoot(appComponentType, null, injector)
.then((componentRef) => {
if (isPresent(componentRef.location.nativeElement)) {
injector.get(TestabilityRegistry)
.registerApplication(componentRef.location.nativeElement,
injector.get(Testability));
}
return componentRef;
});
},
[DynamicComponentLoader, Injector]),
bind(appComponentType)
.toFactory((p: Promise<any>) => p.then(ref => ref.instance), [APP_COMPONENT_REF_PROMISE]),
provide(APP_COMPONENT, {asValue: appComponentType}),
provide(APP_COMPONENT_REF_PROMISE,
{
asFactory: (dynamicComponentLoader, injector: Injector) => {
// TODO(rado): investigate whether to support bindings on root component.
return dynamicComponentLoader.loadAsRoot(appComponentType, null, injector)
.then((componentRef) => {
if (isPresent(componentRef.location.nativeElement)) {
injector.get(TestabilityRegistry)
.registerApplication(componentRef.location.nativeElement,
injector.get(Testability));
}
return componentRef;
});
},
deps: [DynamicComponentLoader, Injector]
}),
provide(appComponentType,
{
asFactory: (p: Promise<any>) => p.then(ref => ref.instance),
deps: [APP_COMPONENT_REF_PROMISE]
}),
];
}
/**
* Construct a default set of bindings which should be included in any Angular
* Construct a default set of providers which should be included in any Angular
* application, regardless of whether it runs on the UI thread or in a web worker.
*/
export function applicationCommonBindings(): Array<Type | Binding | any[]> {
export function applicationCommonBindings(): Array<Type | Provider | any[]> {
return [
bind(Compiler)
.toClass(Compiler_),
APP_ID_RANDOM_BINDING,
provide(Compiler, {asClass: Compiler_}),
APP_ID_RANDOM_PROVIDER,
AppViewPool,
bind(APP_VIEW_POOL_CAPACITY).toValue(10000),
bind(AppViewManager).toClass(AppViewManager_),
provide(APP_VIEW_POOL_CAPACITY, {asValue: 10000}),
provide(AppViewManager, {asClass: AppViewManager_}),
AppViewManagerUtils,
AppViewListener,
ProtoViewFactory,
ViewResolver,
DEFAULT_PIPES,
bind(IterableDiffers).toValue(defaultIterableDiffers),
bind(KeyValueDiffers).toValue(defaultKeyValueDiffers),
provide(IterableDiffers, {asValue: defaultIterableDiffers}),
provide(KeyValueDiffers, {asValue: defaultKeyValueDiffers}),
DirectiveResolver,
PipeResolver,
bind(DynamicComponentLoader).toClass(DynamicComponentLoader_),
bind(LifeCycle).toFactory((exceptionHandler) => new LifeCycle_(null, assertionsEnabled()),
[ExceptionHandler]),
provide(DynamicComponentLoader, {asClass: DynamicComponentLoader_}),
provide(LifeCycle,
{
asFactory: (exceptionHandler) => new LifeCycle_(null, assertionsEnabled()),
deps: [ExceptionHandler]
})
];
}
@ -117,7 +121,7 @@ export function createNgZone(): NgZone {
var _platform: PlatformRef;
export function platformCommon(bindings?: Array<Type | Binding | any[]>, initializer?: () => void):
export function platformCommon(bindings?: Array<Type | Provider | any[]>, initializer?: () => void):
PlatformRef {
if (isPresent(_platform)) {
if (isBlank(bindings)) {
@ -148,7 +152,7 @@ export function platformCommon(bindings?: Array<Type | Binding | any[]>, initial
export abstract class PlatformRef {
/**
* Retrieve the platform {@link Injector}, which is the parent injector for
* every Angular application on the page and provides singleton bindings.
* every Angular application on the page and provides singleton providers.
*/
get injector(): Injector { return unimplemented(); };
@ -163,10 +167,10 @@ export abstract class PlatformRef {
*
* # Application Bindings
*
* Angular applications require numerous bindings to be properly instantiated.
* When using `application()` to create a new app on the page, these bindings
* Angular applications require numerous providers to be properly instantiated.
* When using `application()` to create a new app on the page, these providers
* must be provided. Fortunately, there are helper functions to configure
* typical bindings, as shown in the example below.
* typical providers, as shown in the example below.
*
* # Example
* ```
@ -180,21 +184,21 @@ export abstract class PlatformRef {
*
* See the {@link bootstrap} documentation for more details.
*/
abstract application(bindings: Array<Type | Binding | any[]>): ApplicationRef;
abstract application(bindings: Array<Type | Provider | any[]>): ApplicationRef;
/**
* Instantiate a new Angular application on the page, using bindings which
* Instantiate a new Angular application on the page, using providers which
* are only available asynchronously. One such use case is to initialize an
* application running in a web worker.
*
* # Usage
*
* `bindingFn` is a function that will be called in the new application's zone.
* It should return a {@link Promise} to a list of bindings to be used for the
* It should return a {@link Promise} to a list of providers to be used for the
* new application. Once this promise resolves, the application will be
* constructed in the same manner as a normal `application()`.
*/
abstract asyncApplication(bindingFn: (zone: NgZone) => Promise<Array<Type | Binding | any[]>>):
abstract asyncApplication(bindingFn: (zone: NgZone) => Promise<Array<Type | Provider | any[]>>):
Promise<ApplicationRef>;
/**
@ -211,33 +215,33 @@ export class PlatformRef_ extends PlatformRef {
get injector(): Injector { return this._injector; }
application(bindings: Array<Type | Binding | any[]>): ApplicationRef {
application(bindings: Array<Type | Provider | any[]>): ApplicationRef {
var app = this._initApp(createNgZone(), bindings);
return app;
}
asyncApplication(bindingFn: (zone: NgZone) =>
Promise<Array<Type | Binding | any[]>>): Promise<ApplicationRef> {
Promise<Array<Type | Provider | any[]>>): Promise<ApplicationRef> {
var zone = createNgZone();
var completer = PromiseWrapper.completer();
zone.run(() => {
PromiseWrapper.then(bindingFn(zone), (bindings: Array<Type | Binding | any[]>) => {
PromiseWrapper.then(bindingFn(zone), (bindings: Array<Type | Provider | any[]>) => {
completer.resolve(this._initApp(zone, bindings));
});
});
return completer.promise;
}
private _initApp(zone: NgZone, bindings: Array<Type | Binding | any[]>): ApplicationRef {
private _initApp(zone: NgZone, providers: Array<Type | Provider | any[]>): ApplicationRef {
var injector: Injector;
var app: ApplicationRef;
zone.run(() => {
bindings.push(bind(NgZone).toValue(zone));
bindings.push(bind(ApplicationRef).toFactory((): ApplicationRef => app, []));
providers.push(provide(NgZone, {asValue: zone}));
providers.push(provide(ApplicationRef, {asFactory: (): ApplicationRef => app, deps: []}));
var exceptionHandler;
try {
injector = this.injector.resolveAndCreateChild(bindings);
injector = this.injector.resolveAndCreateChild(providers);
exceptionHandler = injector.get(ExceptionHandler);
zone.overrideOnErrorHandler((e, s) => exceptionHandler.call(e, s));
} catch (e) {
@ -285,18 +289,18 @@ export abstract class ApplicationRef {
*
* # Optional Bindings
*
* Bindings for the given component can optionally be overridden via the `bindings`
* parameter. These bindings will only apply for the root component being added and any
* Bindings for the given component can optionally be overridden via the `providers`
* parameter. These providers will only apply for the root component being added and any
* child components under it.
*
* # Example
* ```
* var app = platform.application([applicationCommonBindings(), applicationDomBindings()];
* app.bootstrap(FirstRootComponent);
* app.bootstrap(SecondRootComponent, [bind(OverrideBinding).toClass(OverriddenBinding)]);
* app.bootstrap(SecondRootComponent, [provide(OverrideBinding, {asClass: OverriddenBinding})]);
* ```
*/
abstract bootstrap(componentType: Type, bindings?: Array<Type | Binding | any[]>):
abstract bootstrap(componentType: Type, bindings?: Array<Type | Provider | any[]>):
Promise<ComponentRef>;
/**
@ -333,17 +337,18 @@ export class ApplicationRef_ extends ApplicationRef {
this._bootstrapListeners.push(listener);
}
bootstrap(componentType: Type, bindings?: Array<Type | Binding | any[]>): Promise<ComponentRef> {
bootstrap(componentType: Type,
providers?: Array<Type | Provider | any[]>): Promise<ComponentRef> {
var completer = PromiseWrapper.completer();
this._zone.run(() => {
var componentBindings = _componentBindings(componentType);
if (isPresent(bindings)) {
componentBindings.push(bindings);
var componentProviders = _componentProviders(componentType);
if (isPresent(providers)) {
componentProviders.push(providers);
}
var exceptionHandler = this._injector.get(ExceptionHandler);
this._rootComponentTypes.push(componentType);
try {
var injector: Injector = this._injector.resolveAndCreateChild(componentBindings);
var injector: Injector = this._injector.resolveAndCreateChild(componentProviders);
var compRefToken: Promise<ComponentRef> = injector.get(APP_COMPONENT_REF_PROMISE);
var tick = (componentRef) => {
var appChangeDetector = internalView(componentRef.hostView).changeDetector;

View File

@ -1,4 +1,4 @@
import {OpaqueToken, Binding} from 'angular2/src/core/di';
import {OpaqueToken, Provider} from 'angular2/src/core/di';
import {CONST_EXPR, Math, StringWrapper} from 'angular2/src/core/facade/lang';
/**
@ -31,20 +31,20 @@ export const APP_COMPONENT: OpaqueToken = CONST_EXPR(new OpaqueToken('AppCompone
* {@link ViewEncapsulation#Emulated} is being used.
*
* If you need to avoid randomly generated value to be used as an application id, you can provide
* a custom value via a DI binding <!-- TODO: provider --> configuring the root {@link Injector}
* a custom value via a DI provider <!-- TODO: provider --> configuring the root {@link Injector}
* using this token.
*/
export const APP_ID: OpaqueToken = CONST_EXPR(new OpaqueToken('AppId'));
function _appIdRandomBindingFactory() {
function _appIdRandomProviderFactory() {
return `${_randomChar()}${_randomChar()}${_randomChar()}`;
}
/**
* Bindings that will generate a random APP_ID_TOKEN.
*/
export const APP_ID_RANDOM_BINDING: Binding =
CONST_EXPR(new Binding(APP_ID, {toFactory: _appIdRandomBindingFactory, deps: []}));
export const APP_ID_RANDOM_PROVIDER: Provider =
CONST_EXPR(new Provider(APP_ID, {toFactory: _appIdRandomProviderFactory, deps: []}));
function _randomChar(): string {
return StringWrapper.fromCharCode(97 + Math.floor(Math.random() * 25));

View File

@ -85,7 +85,7 @@ export abstract class ChangeDetectorRef {
* }
*
* @Component({
* selector: 'app', bindings: [DataProvider]
* selector: 'app', providers: [DataProvider]
* })
* @View({
* template: `
@ -166,7 +166,7 @@ export abstract class ChangeDetectorRef {
*
* @Component({
* selector: 'app',
* bindings: [DataProvider]
* providers: [DataProvider]
* })
* @View({
* template: `

View File

@ -2,7 +2,7 @@ import {isBlank, isPresent, CONST} from 'angular2/src/core/facade/lang';
import {BaseException} from 'angular2/src/core/facade/exceptions';
import {ListWrapper} from 'angular2/src/core/facade/collection';
import {ChangeDetectorRef} from '../change_detector_ref';
import {Binding, SkipSelfMetadata, OptionalMetadata, Injectable} from 'angular2/src/core/di';
import {Provider, SkipSelfMetadata, OptionalMetadata, Injectable} from 'angular2/src/core/di';
export interface IterableDiffer {
diff(object: Object): any;
@ -36,7 +36,7 @@ export class IterableDiffers {
}
/**
* Takes an array of {@link IterableDifferFactory} and returns a binding used to extend the
* Takes an array of {@link IterableDifferFactory} and returns a provider used to extend the
* inherited {@link IterableDiffers} instance with the provided factories and return a new
* {@link IterableDiffers} instance.
*
@ -48,14 +48,14 @@ export class IterableDiffers {
*
* ```
* @Component({
* viewBindings: [
* viewProviders: [
* IterableDiffers.extend([new ImmutableListDiffer()])
* ]
* })
* ```
*/
static extend(factories: IterableDifferFactory[]): Binding {
return new Binding(IterableDiffers, {
static extend(factories: IterableDifferFactory[]): Provider {
return new Provider(IterableDiffers, {
toFactory: (parent: IterableDiffers) => {
if (isBlank(parent)) {
// Typically would occur when calling IterableDiffers.extend inside of dependencies passed

View File

@ -2,7 +2,7 @@ import {isBlank, isPresent, CONST} from 'angular2/src/core/facade/lang';
import {BaseException} from 'angular2/src/core/facade/exceptions';
import {ListWrapper} from 'angular2/src/core/facade/collection';
import {ChangeDetectorRef} from '../change_detector_ref';
import {Binding, SkipSelfMetadata, OptionalMetadata, Injectable} from 'angular2/src/core/di';
import {Provider, SkipSelfMetadata, OptionalMetadata, Injectable} from 'angular2/src/core/di';
export interface KeyValueDiffer {
diff(object: Object);
@ -36,7 +36,7 @@ export class KeyValueDiffers {
}
/**
* Takes an array of {@link KeyValueDifferFactory} and returns a binding used to extend the
* Takes an array of {@link KeyValueDifferFactory} and returns a provider used to extend the
* inherited {@link KeyValueDiffers} instance with the provided factories and return a new
* {@link KeyValueDiffers} instance.
*
@ -48,14 +48,14 @@ export class KeyValueDiffers {
*
* ```
* @Component({
* viewBindings: [
* viewProviders: [
* KeyValueDiffers.extend([new ImmutableMapDiffer()])
* ]
* })
* ```
*/
static extend(factories: KeyValueDifferFactory[]): Binding {
return new Binding(KeyValueDiffers, {
static extend(factories: KeyValueDifferFactory[]): Provider {
return new Provider(KeyValueDiffers, {
toFactory: (parent: KeyValueDiffers) => {
if (isBlank(parent)) {
// Typically would occur when calling KeyValueDiffers.extend inside of dependencies passed

View File

@ -8,7 +8,7 @@ export {
export {SourceModule, SourceWithImports} from './source_module';
import {assertionsEnabled, Type} from 'angular2/src/core/facade/lang';
import {bind, Binding} from 'angular2/src/core/di';
import {provide, Provider} from 'angular2/src/core/di';
import {TemplateParser} from 'angular2/src/core/compiler/template_parser';
import {HtmlParser} from 'angular2/src/core/compiler/html_parser';
import {TemplateNormalizer} from 'angular2/src/core/compiler/template_normalizer';
@ -29,7 +29,7 @@ import {AppRootUrl} from 'angular2/src/core/compiler/app_root_url';
import {AnchorBasedAppRootUrl} from 'angular2/src/core/compiler/anchor_based_app_root_url';
import {Parser, Lexer} from 'angular2/src/core/change_detection/change_detection';
export function compilerBindings(): Array<Type | Binding | any[]> {
export function compilerProviders(): Array<Type | Provider | any[]> {
return [
Lexer,
Parser,
@ -40,16 +40,18 @@ export function compilerBindings(): Array<Type | Binding | any[]> {
StyleCompiler,
CommandCompiler,
ChangeDetectionCompiler,
bind(ChangeDetectorGenConfig)
.toValue(
new ChangeDetectorGenConfig(assertionsEnabled(), assertionsEnabled(), false, true)),
provide(ChangeDetectorGenConfig,
{
asValue:
new ChangeDetectorGenConfig(assertionsEnabled(), assertionsEnabled(), false, true)
}),
TemplateCompiler,
bind(RuntimeCompiler).toClass(RuntimeCompiler_),
bind(Compiler).toAlias(RuntimeCompiler),
provide(RuntimeCompiler, {asClass: RuntimeCompiler_}),
provide(Compiler, {asAlias: RuntimeCompiler}),
DomElementSchemaRegistry,
bind(ElementSchemaRegistry).toAlias(DomElementSchemaRegistry),
provide(ElementSchemaRegistry, {asAlias: DomElementSchemaRegistry}),
AnchorBasedAppRootUrl,
bind(AppRootUrl).toAlias(AnchorBasedAppRootUrl),
provide(AppRootUrl, {asAlias: AnchorBasedAppRootUrl}),
UrlResolver
];
}

View File

@ -1,2 +1,6 @@
export {DebugElement, asNativeElements, By, Scope, inspectElement} from './debug/debug_element';
export {inspectNativeElement, ELEMENT_PROBE_BINDINGS} from './debug/debug_element_view_listener';
export {
inspectNativeElement,
ELEMENT_PROBE_PROVIDERS,
ELEMENT_PROBE_BINDINGS
} from './debug/debug_element_view_listener';

View File

@ -1,6 +1,6 @@
import {CONST_EXPR, isPresent, NumberWrapper, StringWrapper} from 'angular2/src/core/facade/lang';
import {MapWrapper, Map, ListWrapper} from 'angular2/src/core/facade/collection';
import {Injectable, bind, Binding} from 'angular2/src/core/di';
import {Injectable, provide, Provider} from 'angular2/src/core/di';
import {AppViewListener} from 'angular2/src/core/linker/view_listener';
import {AppView} from 'angular2/src/core/linker/view';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
@ -67,7 +67,9 @@ export class DebugElementViewListener implements AppViewListener {
}
}
export const ELEMENT_PROBE_BINDINGS: any[] = CONST_EXPR([
export const ELEMENT_PROBE_PROVIDERS: any[] = CONST_EXPR([
DebugElementViewListener,
CONST_EXPR(new Binding(AppViewListener, {toAlias: DebugElementViewListener})),
CONST_EXPR(new Provider(AppViewListener, {toAlias: DebugElementViewListener})),
]);
export const ELEMENT_PROBE_BINDINGS = ELEMENT_PROBE_PROVIDERS;

View File

@ -21,19 +21,23 @@ export {forwardRef, resolveForwardRef, ForwardRefFn} from './di/forward_ref';
export {Injector} from './di/injector';
export {
Binding,
BindingBuilder,
ProviderBuilder,
ResolvedBinding,
ResolvedFactory,
Dependency,
bind
} from './di/binding';
bind,
Provider,
ResolvedProvider,
provide
} from './di/provider';
export {Key, TypeLiteral} from './di/key';
export {
NoBindingError,
AbstractBindingError,
NoProviderError,
AbstractProviderError,
CyclicDependencyError,
InstantiationError,
InvalidBindingError,
InvalidProviderError,
NoAnnotationError,
OutOfBoundsError
} from './di/exceptions';

View File

@ -29,9 +29,9 @@ function constructResolvingPath(keys: any[]): string {
/**
* Base class for all errors arising from misconfigured bindings.
* Base class for all errors arising from misconfigured providers.
*/
export class AbstractBindingError extends BaseException {
export class AbstractProviderError extends BaseException {
/** @internal */
message: string;
@ -63,7 +63,7 @@ export class AbstractBindingError extends BaseException {
/**
* Thrown when trying to retrieve a dependency by `Key` from {@link Injector}, but the
* {@link Injector} does not have a {@link Binding} for {@link Key}.
* {@link Injector} does not have a {@link Provider} for {@link Key}.
*
* ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview))
*
@ -75,7 +75,7 @@ export class AbstractBindingError extends BaseException {
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
* ```
*/
export class NoBindingError extends AbstractBindingError {
export class NoProviderError extends AbstractProviderError {
constructor(injector: Injector, key: Key) {
super(injector, key, function(keys: any[]) {
var first = stringify(ListWrapper.first(keys).token);
@ -91,8 +91,8 @@ export class NoBindingError extends AbstractBindingError {
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* bind("one").toFactory((two) => "two", [[new Inject("two")]]),
* bind("two").toFactory((one) => "one", [[new Inject("one")]])
* provide("one", {asFactory: (two) => "two", deps: [[new Inject("two")]]}),
* provide("two", {asFactory: (one) => "one", deps: [[new Inject("one")]]})
* ]);
*
* expect(() => injector.get("one")).toThrowError();
@ -100,7 +100,7 @@ export class NoBindingError extends AbstractBindingError {
*
* Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
*/
export class CyclicDependencyError extends AbstractBindingError {
export class CyclicDependencyError extends AbstractProviderError {
constructor(injector: Injector, key: Key) {
super(injector, key, function(keys: any[]) {
return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`;
@ -163,7 +163,7 @@ export class InstantiationError extends WrappedException {
}
/**
* Thrown when an object other then {@link Binding} (or `Type`) is passed to {@link Injector}
* Thrown when an object other then {@link Provider} (or `Type`) is passed to {@link Injector}
* creation.
*
* ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview))
@ -172,10 +172,10 @@ export class InstantiationError extends WrappedException {
* expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError();
* ```
*/
export class InvalidBindingError extends BaseException {
constructor(binding) {
super("Invalid binding - only instances of Binding and Type are allowed, got: " +
binding.toString());
export class InvalidProviderError extends BaseException {
constructor(provider) {
super("Invalid provider - only instances of Provider and Type are allowed, got: " +
provider.toString());
}
}
@ -246,20 +246,20 @@ export class OutOfBoundsError extends BaseException {
// TODO: add a working example after alpha38 is released
/**
* Thrown when a multi binding and a regular binding are bound to the same token.
* Thrown when a multi provider and a regular provider are bound to the same token.
*
* ### Example
*
* ```typescript
* expect(() => Injector.resolveAndCreate([
* new Binding("Strings", {toValue: "string1", multi: true}),
* new Binding("Strings", {toValue: "string2", multi: false})
* new Provider("Strings", {toValue: "string1", multi: true}),
* new Provider("Strings", {toValue: "string2", multi: false})
* ])).toThrowError();
* ```
*/
export class MixingMultiBindingsWithRegularBindings extends BaseException {
constructor(binding1, binding2) {
super("Cannot mix multi bindings and regular bindings, got: " + binding1.toString() + " " +
binding2.toString());
export class MixingMultiProvidersWithRegularProvidersError extends BaseException {
constructor(provider1, provider2) {
super("Cannot mix multi providers and regular providers, got: " + provider1.toString() + " " +
provider2.toString());
}
}

View File

@ -1,21 +1,20 @@
import {Map, MapWrapper, ListWrapper} from 'angular2/src/core/facade/collection';
import {
ResolvedBinding,
Binding,
ResolvedProvider,
Provider,
Dependency,
BindingBuilder,
ProviderBuilder,
ResolvedFactory,
bind,
resolveBindings
} from './binding';
provide,
resolveProviders
} from './provider';
import {
AbstractBindingError,
NoBindingError,
AbstractProviderError,
NoProviderError,
CyclicDependencyError,
InstantiationError,
InvalidBindingError,
OutOfBoundsError,
MixingMultiBindingsWithRegularBindings
InvalidProviderError,
OutOfBoundsError
} from './exceptions';
import {FunctionWrapper, Type, isPresent, isBlank, CONST_EXPR} from 'angular2/src/core/facade/lang';
import {Key} from './key';
@ -28,19 +27,19 @@ const _MAX_CONSTRUCTION_COUNTER = 10;
export const UNDEFINED: Object = CONST_EXPR(new Object());
/**
* Visibility of a {@link Binding}.
* Visibility of a {@link Provider}.
*/
export enum Visibility {
/**
* A `Public` {@link Binding} is only visible to regular (as opposed to host) child injectors.
* A `Public` {@link Provider} is only visible to regular (as opposed to host) child injectors.
*/
Public,
/**
* A `Private` {@link Binding} is only visible to host (as opposed to regular) child injectors.
* A `Private` {@link Provider} is only visible to host (as opposed to regular) child injectors.
*/
Private,
/**
* A `PublicAndPrivate` {@link Binding} is visible to both host and regular child injectors.
* A `PublicAndPrivate` {@link Provider} is visible to both host and regular child injectors.
*/
PublicAndPrivate
}
@ -52,21 +51,21 @@ function canSee(src: Visibility, dst: Visibility): boolean {
export interface ProtoInjectorStrategy {
getBindingAtIndex(index: number): ResolvedBinding;
getProviderAtIndex(index: number): ResolvedProvider;
createInjectorStrategy(inj: Injector): InjectorStrategy;
}
export class ProtoInjectorInlineStrategy implements ProtoInjectorStrategy {
binding0: ResolvedBinding = null;
binding1: ResolvedBinding = null;
binding2: ResolvedBinding = null;
binding3: ResolvedBinding = null;
binding4: ResolvedBinding = null;
binding5: ResolvedBinding = null;
binding6: ResolvedBinding = null;
binding7: ResolvedBinding = null;
binding8: ResolvedBinding = null;
binding9: ResolvedBinding = null;
provider0: ResolvedProvider = null;
provider1: ResolvedProvider = null;
provider2: ResolvedProvider = null;
provider3: ResolvedProvider = null;
provider4: ResolvedProvider = null;
provider5: ResolvedProvider = null;
provider6: ResolvedProvider = null;
provider7: ResolvedProvider = null;
provider8: ResolvedProvider = null;
provider9: ResolvedProvider = null;
keyId0: number = null;
keyId1: number = null;
@ -90,72 +89,72 @@ export class ProtoInjectorInlineStrategy implements ProtoInjectorStrategy {
visibility8: Visibility = null;
visibility9: Visibility = null;
constructor(protoEI: ProtoInjector, bwv: BindingWithVisibility[]) {
constructor(protoEI: ProtoInjector, bwv: ProviderWithVisibility[]) {
var length = bwv.length;
if (length > 0) {
this.binding0 = bwv[0].binding;
this.provider0 = bwv[0].provider;
this.keyId0 = bwv[0].getKeyId();
this.visibility0 = bwv[0].visibility;
}
if (length > 1) {
this.binding1 = bwv[1].binding;
this.provider1 = bwv[1].provider;
this.keyId1 = bwv[1].getKeyId();
this.visibility1 = bwv[1].visibility;
}
if (length > 2) {
this.binding2 = bwv[2].binding;
this.provider2 = bwv[2].provider;
this.keyId2 = bwv[2].getKeyId();
this.visibility2 = bwv[2].visibility;
}
if (length > 3) {
this.binding3 = bwv[3].binding;
this.provider3 = bwv[3].provider;
this.keyId3 = bwv[3].getKeyId();
this.visibility3 = bwv[3].visibility;
}
if (length > 4) {
this.binding4 = bwv[4].binding;
this.provider4 = bwv[4].provider;
this.keyId4 = bwv[4].getKeyId();
this.visibility4 = bwv[4].visibility;
}
if (length > 5) {
this.binding5 = bwv[5].binding;
this.provider5 = bwv[5].provider;
this.keyId5 = bwv[5].getKeyId();
this.visibility5 = bwv[5].visibility;
}
if (length > 6) {
this.binding6 = bwv[6].binding;
this.provider6 = bwv[6].provider;
this.keyId6 = bwv[6].getKeyId();
this.visibility6 = bwv[6].visibility;
}
if (length > 7) {
this.binding7 = bwv[7].binding;
this.provider7 = bwv[7].provider;
this.keyId7 = bwv[7].getKeyId();
this.visibility7 = bwv[7].visibility;
}
if (length > 8) {
this.binding8 = bwv[8].binding;
this.provider8 = bwv[8].provider;
this.keyId8 = bwv[8].getKeyId();
this.visibility8 = bwv[8].visibility;
}
if (length > 9) {
this.binding9 = bwv[9].binding;
this.provider9 = bwv[9].provider;
this.keyId9 = bwv[9].getKeyId();
this.visibility9 = bwv[9].visibility;
}
}
getBindingAtIndex(index: number): any {
if (index == 0) return this.binding0;
if (index == 1) return this.binding1;
if (index == 2) return this.binding2;
if (index == 3) return this.binding3;
if (index == 4) return this.binding4;
if (index == 5) return this.binding5;
if (index == 6) return this.binding6;
if (index == 7) return this.binding7;
if (index == 8) return this.binding8;
if (index == 9) return this.binding9;
getProviderAtIndex(index: number): any {
if (index == 0) return this.provider0;
if (index == 1) return this.provider1;
if (index == 2) return this.provider2;
if (index == 3) return this.provider3;
if (index == 4) return this.provider4;
if (index == 5) return this.provider5;
if (index == 6) return this.provider6;
if (index == 7) return this.provider7;
if (index == 8) return this.provider8;
if (index == 9) return this.provider9;
throw new OutOfBoundsError(index);
}
@ -165,29 +164,29 @@ export class ProtoInjectorInlineStrategy implements ProtoInjectorStrategy {
}
export class ProtoInjectorDynamicStrategy implements ProtoInjectorStrategy {
bindings: ResolvedBinding[];
providers: ResolvedProvider[];
keyIds: number[];
visibilities: Visibility[];
constructor(protoInj: ProtoInjector, bwv: BindingWithVisibility[]) {
constructor(protoInj: ProtoInjector, bwv: ProviderWithVisibility[]) {
var len = bwv.length;
this.bindings = ListWrapper.createFixedSize(len);
this.providers = ListWrapper.createFixedSize(len);
this.keyIds = ListWrapper.createFixedSize(len);
this.visibilities = ListWrapper.createFixedSize(len);
for (var i = 0; i < len; i++) {
this.bindings[i] = bwv[i].binding;
this.providers[i] = bwv[i].provider;
this.keyIds[i] = bwv[i].getKeyId();
this.visibilities[i] = bwv[i].visibility;
}
}
getBindingAtIndex(index: number): any {
if (index < 0 || index >= this.bindings.length) {
getProviderAtIndex(index: number): any {
if (index < 0 || index >= this.providers.length) {
throw new OutOfBoundsError(index);
}
return this.bindings[index];
return this.providers[index];
}
createInjectorStrategy(ei: Injector): InjectorStrategy {
@ -198,16 +197,16 @@ export class ProtoInjectorDynamicStrategy implements ProtoInjectorStrategy {
export class ProtoInjector {
/** @internal */
_strategy: ProtoInjectorStrategy;
numberOfBindings: number;
numberOfProviders: number;
constructor(bwv: BindingWithVisibility[]) {
this.numberOfBindings = bwv.length;
constructor(bwv: ProviderWithVisibility[]) {
this.numberOfProviders = bwv.length;
this._strategy = bwv.length > _MAX_CONSTRUCTION_COUNTER ?
new ProtoInjectorDynamicStrategy(this, bwv) :
new ProtoInjectorInlineStrategy(this, bwv);
}
getBindingAtIndex(index: number): any { return this._strategy.getBindingAtIndex(index); }
getProviderAtIndex(index: number): any { return this._strategy.getProviderAtIndex(index); }
}
@ -219,7 +218,7 @@ export interface InjectorStrategy {
attach(parent: Injector, isHost: boolean): void;
resetConstructionCounter(): void;
instantiateBinding(binding: ResolvedBinding, visibility: Visibility): any;
instantiateProvider(provider: ResolvedProvider, visibility: Visibility): any;
}
export class InjectorInlineStrategy implements InjectorStrategy {
@ -238,8 +237,8 @@ export class InjectorInlineStrategy implements InjectorStrategy {
resetConstructionCounter(): void { this.injector._constructionCounter = 0; }
instantiateBinding(binding: ResolvedBinding, visibility: Visibility): any {
return this.injector._new(binding, visibility);
instantiateProvider(provider: ResolvedProvider, visibility: Visibility): any {
return this.injector._new(provider, visibility);
}
attach(parent: Injector, isHost: boolean): void {
@ -254,61 +253,61 @@ export class InjectorInlineStrategy implements InjectorStrategy {
if (p.keyId0 === keyId && canSee(p.visibility0, visibility)) {
if (this.obj0 === UNDEFINED) {
this.obj0 = inj._new(p.binding0, p.visibility0);
this.obj0 = inj._new(p.provider0, p.visibility0);
}
return this.obj0;
}
if (p.keyId1 === keyId && canSee(p.visibility1, visibility)) {
if (this.obj1 === UNDEFINED) {
this.obj1 = inj._new(p.binding1, p.visibility1);
this.obj1 = inj._new(p.provider1, p.visibility1);
}
return this.obj1;
}
if (p.keyId2 === keyId && canSee(p.visibility2, visibility)) {
if (this.obj2 === UNDEFINED) {
this.obj2 = inj._new(p.binding2, p.visibility2);
this.obj2 = inj._new(p.provider2, p.visibility2);
}
return this.obj2;
}
if (p.keyId3 === keyId && canSee(p.visibility3, visibility)) {
if (this.obj3 === UNDEFINED) {
this.obj3 = inj._new(p.binding3, p.visibility3);
this.obj3 = inj._new(p.provider3, p.visibility3);
}
return this.obj3;
}
if (p.keyId4 === keyId && canSee(p.visibility4, visibility)) {
if (this.obj4 === UNDEFINED) {
this.obj4 = inj._new(p.binding4, p.visibility4);
this.obj4 = inj._new(p.provider4, p.visibility4);
}
return this.obj4;
}
if (p.keyId5 === keyId && canSee(p.visibility5, visibility)) {
if (this.obj5 === UNDEFINED) {
this.obj5 = inj._new(p.binding5, p.visibility5);
this.obj5 = inj._new(p.provider5, p.visibility5);
}
return this.obj5;
}
if (p.keyId6 === keyId && canSee(p.visibility6, visibility)) {
if (this.obj6 === UNDEFINED) {
this.obj6 = inj._new(p.binding6, p.visibility6);
this.obj6 = inj._new(p.provider6, p.visibility6);
}
return this.obj6;
}
if (p.keyId7 === keyId && canSee(p.visibility7, visibility)) {
if (this.obj7 === UNDEFINED) {
this.obj7 = inj._new(p.binding7, p.visibility7);
this.obj7 = inj._new(p.provider7, p.visibility7);
}
return this.obj7;
}
if (p.keyId8 === keyId && canSee(p.visibility8, visibility)) {
if (this.obj8 === UNDEFINED) {
this.obj8 = inj._new(p.binding8, p.visibility8);
this.obj8 = inj._new(p.provider8, p.visibility8);
}
return this.obj8;
}
if (p.keyId9 === keyId && canSee(p.visibility9, visibility)) {
if (this.obj9 === UNDEFINED) {
this.obj9 = inj._new(p.binding9, p.visibility9);
this.obj9 = inj._new(p.provider9, p.visibility9);
}
return this.obj9;
}
@ -338,14 +337,14 @@ export class InjectorDynamicStrategy implements InjectorStrategy {
objs: any[];
constructor(public protoStrategy: ProtoInjectorDynamicStrategy, public injector: Injector) {
this.objs = ListWrapper.createFixedSize(protoStrategy.bindings.length);
this.objs = ListWrapper.createFixedSize(protoStrategy.providers.length);
ListWrapper.fill(this.objs, UNDEFINED);
}
resetConstructionCounter(): void { this.injector._constructionCounter = 0; }
instantiateBinding(binding: ResolvedBinding, visibility: Visibility): any {
return this.injector._new(binding, visibility);
instantiateProvider(provider: ResolvedProvider, visibility: Visibility): any {
return this.injector._new(provider, visibility);
}
attach(parent: Injector, isHost: boolean): void {
@ -360,7 +359,7 @@ export class InjectorDynamicStrategy implements InjectorStrategy {
for (var i = 0; i < p.keyIds.length; i++) {
if (p.keyIds[i] === keyId && canSee(p.visibilities[i], visibility)) {
if (this.objs[i] === UNDEFINED) {
this.objs[i] = this.injector._new(p.bindings[i], p.visibilities[i]);
this.objs[i] = this.injector._new(p.providers[i], p.visibilities[i]);
}
return this.objs[i];
@ -381,17 +380,17 @@ export class InjectorDynamicStrategy implements InjectorStrategy {
getMaxNumberOfObjects(): number { return this.objs.length; }
}
export class BindingWithVisibility {
constructor(public binding: ResolvedBinding, public visibility: Visibility){};
export class ProviderWithVisibility {
constructor(public provider: ResolvedProvider, public visibility: Visibility){};
getKeyId(): number { return this.binding.key.id; }
getKeyId(): number { return this.provider.key.id; }
}
/**
* Used to provide dependencies that cannot be easily expressed as bindings.
* Used to provide dependencies that cannot be easily expressed as providers.
*/
export interface DependencyProvider {
getDependency(injector: Injector, binding: ResolvedBinding, dependency: Dependency): any;
getDependency(injector: Injector, provider: ResolvedProvider, dependency: Dependency): any;
}
/**
@ -428,10 +427,10 @@ export interface DependencyProvider {
*/
export class Injector {
/**
* Turns an array of binding definitions into an array of resolved bindings.
* Turns an array of provider definitions into an array of resolved providers.
*
* A resolution is a process of flattening multiple nested arrays and converting individual
* bindings into an array of {@link ResolvedBinding}s.
* providers into an array of {@link ResolvedProvider}s.
*
* ### Example ([live demo](http://plnkr.co/edit/AiXTHi?p=preview))
*
@ -445,30 +444,30 @@ export class Injector {
* constructor(public engine:Engine) {}
* }
*
* var bindings = Injector.resolve([Car, [[Engine]]]);
* var providers = Injector.resolve([Car, [[Engine]]]);
*
* expect(bindings.length).toEqual(2);
* expect(providers.length).toEqual(2);
*
* expect(bindings[0] instanceof ResolvedBinding).toBe(true);
* expect(bindings[0].key.displayName).toBe("Car");
* expect(bindings[0].dependencies.length).toEqual(1);
* expect(bindings[0].factory).toBeDefined();
* expect(providers[0] instanceof ResolvedProvider).toBe(true);
* expect(providers[0].key.displayName).toBe("Car");
* expect(providers[0].dependencies.length).toEqual(1);
* expect(providers[0].factory).toBeDefined();
*
* expect(bindings[1].key.displayName).toBe("Engine");
* expect(providers[1].key.displayName).toBe("Engine");
* });
* ```
*
* See {@link fromResolvedBindings} for more info.
* See {@link fromResolvedProviders} for more info.
*/
static resolve(bindings: Array<Type | Binding | any[]>): ResolvedBinding[] {
return resolveBindings(bindings);
static resolve(providers: Array<Type | Provider | any[]>): ResolvedProvider[] {
return resolveProviders(providers);
}
/**
* Resolves an array of bindings and creates an injector from those bindings.
* Resolves an array of providers and creates an injector from those providers.
*
* The passed-in bindings can be an array of `Type`, {@link Binding},
* or a recursive array of more bindings.
* The passed-in providers can be an array of `Type`, {@link Provider},
* or a recursive array of more providers.
*
* ### Example ([live demo](http://plnkr.co/edit/ePOccA?p=preview))
*
@ -486,17 +485,17 @@ export class Injector {
* expect(injector.get(Car) instanceof Car).toBe(true);
* ```
*
* This function is slower than the corresponding `fromResolvedBindings`
* because it needs to resolve the passed-in bindings first.
* See {@link resolve} and {@link fromResolvedBindings}.
* This function is slower than the corresponding `fromResolvedProviders`
* because it needs to resolve the passed-in providers first.
* See {@link resolve} and {@link fromResolvedProviders}.
*/
static resolveAndCreate(bindings: Array<Type | Binding | any[]>): Injector {
var resolvedBindings = Injector.resolve(bindings);
return Injector.fromResolvedBindings(resolvedBindings);
static resolveAndCreate(providers: Array<Type | Provider | any[]>): Injector {
var resolvedProviders = Injector.resolve(providers);
return Injector.fromResolvedProviders(resolvedProviders);
}
/**
* Creates an injector from previously resolved bindings.
* Creates an injector from previously resolved providers.
*
* This API is the recommended way to construct injectors in performance-sensitive parts.
*
@ -512,17 +511,24 @@ export class Injector {
* constructor(public engine:Engine) {}
* }
*
* var bindings = Injector.resolve([Car, Engine]);
* var injector = Injector.fromResolvedBindings(bindings);
* var providers = Injector.resolve([Car, Engine]);
* var injector = Injector.fromResolvedProviders(providers);
* expect(injector.get(Car) instanceof Car).toBe(true);
* ```
*/
static fromResolvedBindings(bindings: ResolvedBinding[]): Injector {
var bd = bindings.map(b => new BindingWithVisibility(b, Visibility.Public));
static fromResolvedProviders(providers: ResolvedProvider[]): Injector {
var bd = providers.map(b => new ProviderWithVisibility(b, Visibility.Public));
var proto = new ProtoInjector(bd);
return new Injector(proto, null, null);
}
/**
* @deprecated
*/
static fromResolvedBindings(providers: ResolvedProvider[]): Injector {
return Injector.fromResolvedProviders(providers);
}
/** @internal */
_strategy: InjectorStrategy;
/** @internal */
@ -551,13 +557,13 @@ export class Injector {
/**
* Retrieves an instance from the injector based on the provided token.
* Throws {@link NoBindingError} if not found.
* Throws {@link NoProviderError} if not found.
*
* ### Example ([live demo](http://plnkr.co/edit/HeXSHg?p=preview))
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* bind("validToken").toValue("Value")
* provide("validToken", {asValue: "Value"})
* ]);
* expect(injector.get("validToken")).toEqual("Value");
* expect(() => injector.get("invalidToken")).toThrowError();
@ -582,7 +588,7 @@ export class Injector {
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* bind("validToken").toValue("Value")
* provide("validToken", {asValue: "Value"})
* ]);
* expect(injector.getOptional("validToken")).toEqual("Value");
* expect(injector.getOptional("invalidToken")).toBe(null);
@ -628,39 +634,39 @@ export class Injector {
get internalStrategy(): any { return this._strategy; }
/**
* Resolves an array of bindings and creates a child injector from those bindings.
* Resolves an array of providers and creates a child injector from those providers.
*
* <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
* -->
*
* The passed-in bindings can be an array of `Type`, {@link Binding},
* or a recursive array of more bindings.
* The passed-in providers can be an array of `Type`, {@link Provider},
* or a recursive array of more providers.
*
* ### Example ([live demo](http://plnkr.co/edit/opB3T4?p=preview))
*
* ```typescript
* class ParentBinding {}
* class ChildBinding {}
* class ParentProvider {}
* class ChildProvider {}
*
* var parent = Injector.resolveAndCreate([ParentBinding]);
* var child = parent.resolveAndCreateChild([ChildBinding]);
* var parent = Injector.resolveAndCreate([ParentProvider]);
* var child = parent.resolveAndCreateChild([ChildProvider]);
*
* expect(child.get(ParentBinding) instanceof ParentBinding).toBe(true);
* expect(child.get(ChildBinding) instanceof ChildBinding).toBe(true);
* expect(child.get(ParentBinding)).toBe(parent.get(ParentBinding));
* expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);
* expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);
* expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
* ```
*
* This function is slower than the corresponding `createChildFromResolved`
* because it needs to resolve the passed-in bindings first.
* because it needs to resolve the passed-in providers first.
* See {@link resolve} and {@link createChildFromResolved}.
*/
resolveAndCreateChild(bindings: Array<Type | Binding | any[]>): Injector {
var resolvedBindings = Injector.resolve(bindings);
return this.createChildFromResolved(resolvedBindings);
resolveAndCreateChild(providers: Array<Type | Provider | any[]>): Injector {
var resolvedProviders = Injector.resolve(providers);
return this.createChildFromResolved(resolvedProviders);
}
/**
* Creates a child injector from previously resolved bindings.
* Creates a child injector from previously resolved providers.
*
* <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
* -->
@ -670,22 +676,22 @@ export class Injector {
* ### Example ([live demo](http://plnkr.co/edit/VhyfjN?p=preview))
*
* ```typescript
* class ParentBinding {}
* class ChildBinding {}
* class ParentProvider {}
* class ChildProvider {}
*
* var parentBindings = Injector.resolve([ParentBinding]);
* var childBindings = Injector.resolve([ChildBinding]);
* var parentProviders = Injector.resolve([ParentProvider]);
* var childProviders = Injector.resolve([ChildProvider]);
*
* var parent = Injector.fromResolvedBindings(parentBindings);
* var child = parent.createChildFromResolved(childBindings);
* var parent = Injector.fromResolvedProviders(parentProviders);
* var child = parent.createChildFromResolved(childProviders);
*
* expect(child.get(ParentBinding) instanceof ParentBinding).toBe(true);
* expect(child.get(ChildBinding) instanceof ChildBinding).toBe(true);
* expect(child.get(ParentBinding)).toBe(parent.get(ParentBinding));
* expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);
* expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);
* expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
* ```
*/
createChildFromResolved(bindings: ResolvedBinding[]): Injector {
var bd = bindings.map(b => new BindingWithVisibility(b, Visibility.Public));
createChildFromResolved(providers: ResolvedProvider[]): Injector {
var bd = providers.map(b => new ProviderWithVisibility(b, Visibility.Public));
var proto = new ProtoInjector(bd);
var inj = new Injector(proto, null, null);
inj._parent = this;
@ -693,7 +699,7 @@ export class Injector {
}
/**
* Resolves a binding and instantiates an object in the context of the injector.
* Resolves a provider and instantiates an object in the context of the injector.
*
* The created object does not get cached by the injector.
*
@ -716,12 +722,12 @@ export class Injector {
* expect(car).not.toBe(injector.resolveAndInstantiate(Car));
* ```
*/
resolveAndInstantiate(binding: Type | Binding): any {
return this.instantiateResolved(Injector.resolve([binding])[0]);
resolveAndInstantiate(provider: Type | Provider): any {
return this.instantiateResolved(Injector.resolve([provider])[0]);
}
/**
* Instantiates an object using a resolved binding in the context of the injector.
* Instantiates an object using a resolved provider in the context of the injector.
*
* The created object does not get cached by the injector.
*
@ -738,37 +744,37 @@ export class Injector {
* }
*
* var injector = Injector.resolveAndCreate([Engine]);
* var carBinding = Injector.resolve([Car])[0];
* var car = injector.instantiateResolved(carBinding);
* var carProvider = Injector.resolve([Car])[0];
* var car = injector.instantiateResolved(carProvider);
* expect(car.engine).toBe(injector.get(Engine));
* expect(car).not.toBe(injector.instantiateResolved(carBinding));
* expect(car).not.toBe(injector.instantiateResolved(carProvider));
* ```
*/
instantiateResolved(binding: ResolvedBinding): any {
return this._instantiateBinding(binding, Visibility.PublicAndPrivate);
instantiateResolved(provider: ResolvedProvider): any {
return this._instantiateProvider(provider, Visibility.PublicAndPrivate);
}
/** @internal */
_new(binding: ResolvedBinding, visibility: Visibility): any {
_new(provider: ResolvedProvider, visibility: Visibility): any {
if (this._constructionCounter++ > this._strategy.getMaxNumberOfObjects()) {
throw new CyclicDependencyError(this, binding.key);
throw new CyclicDependencyError(this, provider.key);
}
return this._instantiateBinding(binding, visibility);
return this._instantiateProvider(provider, visibility);
}
private _instantiateBinding(binding: ResolvedBinding, visibility: Visibility): any {
if (binding.multiBinding) {
var res = ListWrapper.createFixedSize(binding.resolvedFactories.length);
for (var i = 0; i < binding.resolvedFactories.length; ++i) {
res[i] = this._instantiate(binding, binding.resolvedFactories[i], visibility);
private _instantiateProvider(provider: ResolvedProvider, visibility: Visibility): any {
if (provider.multiProvider) {
var res = ListWrapper.createFixedSize(provider.resolvedFactories.length);
for (var i = 0; i < provider.resolvedFactories.length; ++i) {
res[i] = this._instantiate(provider, provider.resolvedFactories[i], visibility);
}
return res;
} else {
return this._instantiate(binding, binding.resolvedFactories[0], visibility);
return this._instantiate(provider, provider.resolvedFactories[0], visibility);
}
}
private _instantiate(binding: ResolvedBinding, resolvedFactory: ResolvedFactory,
private _instantiate(provider: ResolvedProvider, resolvedFactory: ResolvedFactory,
visibility: Visibility): any {
var factory = resolvedFactory.factory;
var deps = resolvedFactory.dependencies;
@ -776,29 +782,29 @@ export class Injector {
var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19;
try {
d0 = length > 0 ? this._getByDependency(binding, deps[0], visibility) : null;
d1 = length > 1 ? this._getByDependency(binding, deps[1], visibility) : null;
d2 = length > 2 ? this._getByDependency(binding, deps[2], visibility) : null;
d3 = length > 3 ? this._getByDependency(binding, deps[3], visibility) : null;
d4 = length > 4 ? this._getByDependency(binding, deps[4], visibility) : null;
d5 = length > 5 ? this._getByDependency(binding, deps[5], visibility) : null;
d6 = length > 6 ? this._getByDependency(binding, deps[6], visibility) : null;
d7 = length > 7 ? this._getByDependency(binding, deps[7], visibility) : null;
d8 = length > 8 ? this._getByDependency(binding, deps[8], visibility) : null;
d9 = length > 9 ? this._getByDependency(binding, deps[9], visibility) : null;
d10 = length > 10 ? this._getByDependency(binding, deps[10], visibility) : null;
d11 = length > 11 ? this._getByDependency(binding, deps[11], visibility) : null;
d12 = length > 12 ? this._getByDependency(binding, deps[12], visibility) : null;
d13 = length > 13 ? this._getByDependency(binding, deps[13], visibility) : null;
d14 = length > 14 ? this._getByDependency(binding, deps[14], visibility) : null;
d15 = length > 15 ? this._getByDependency(binding, deps[15], visibility) : null;
d16 = length > 16 ? this._getByDependency(binding, deps[16], visibility) : null;
d17 = length > 17 ? this._getByDependency(binding, deps[17], visibility) : null;
d18 = length > 18 ? this._getByDependency(binding, deps[18], visibility) : null;
d19 = length > 19 ? this._getByDependency(binding, deps[19], visibility) : null;
d0 = length > 0 ? this._getByDependency(provider, deps[0], visibility) : null;
d1 = length > 1 ? this._getByDependency(provider, deps[1], visibility) : null;
d2 = length > 2 ? this._getByDependency(provider, deps[2], visibility) : null;
d3 = length > 3 ? this._getByDependency(provider, deps[3], visibility) : null;
d4 = length > 4 ? this._getByDependency(provider, deps[4], visibility) : null;
d5 = length > 5 ? this._getByDependency(provider, deps[5], visibility) : null;
d6 = length > 6 ? this._getByDependency(provider, deps[6], visibility) : null;
d7 = length > 7 ? this._getByDependency(provider, deps[7], visibility) : null;
d8 = length > 8 ? this._getByDependency(provider, deps[8], visibility) : null;
d9 = length > 9 ? this._getByDependency(provider, deps[9], visibility) : null;
d10 = length > 10 ? this._getByDependency(provider, deps[10], visibility) : null;
d11 = length > 11 ? this._getByDependency(provider, deps[11], visibility) : null;
d12 = length > 12 ? this._getByDependency(provider, deps[12], visibility) : null;
d13 = length > 13 ? this._getByDependency(provider, deps[13], visibility) : null;
d14 = length > 14 ? this._getByDependency(provider, deps[14], visibility) : null;
d15 = length > 15 ? this._getByDependency(provider, deps[15], visibility) : null;
d16 = length > 16 ? this._getByDependency(provider, deps[16], visibility) : null;
d17 = length > 17 ? this._getByDependency(provider, deps[17], visibility) : null;
d18 = length > 18 ? this._getByDependency(provider, deps[18], visibility) : null;
d19 = length > 19 ? this._getByDependency(provider, deps[19], visibility) : null;
} catch (e) {
if (e instanceof AbstractBindingError || e instanceof InstantiationError) {
e.addKey(this, binding.key);
if (e instanceof AbstractProviderError || e instanceof InstantiationError) {
e.addKey(this, provider.key);
}
throw e;
}
@ -874,38 +880,38 @@ export class Injector {
break;
}
} catch (e) {
throw new InstantiationError(this, e, e.stack, binding.key);
throw new InstantiationError(this, e, e.stack, provider.key);
}
return obj;
}
private _getByDependency(binding: ResolvedBinding, dep: Dependency,
bindingVisibility: Visibility): any {
private _getByDependency(provider: ResolvedProvider, dep: Dependency,
providerVisibility: Visibility): any {
var special = isPresent(this._depProvider) ?
this._depProvider.getDependency(this, binding, dep) :
this._depProvider.getDependency(this, provider, dep) :
UNDEFINED;
if (special !== UNDEFINED) {
return special;
} else {
return this._getByKey(dep.key, dep.lowerBoundVisibility, dep.upperBoundVisibility,
dep.optional, bindingVisibility);
dep.optional, providerVisibility);
}
}
private _getByKey(key: Key, lowerBoundVisibility: Object, upperBoundVisibility: Object,
optional: boolean, bindingVisibility: Visibility): any {
optional: boolean, providerVisibility: Visibility): any {
if (key === INJECTOR_KEY) {
return this;
}
if (upperBoundVisibility instanceof SelfMetadata) {
return this._getByKeySelf(key, optional, bindingVisibility);
return this._getByKeySelf(key, optional, providerVisibility);
} else if (upperBoundVisibility instanceof HostMetadata) {
return this._getByKeyHost(key, optional, bindingVisibility, lowerBoundVisibility);
return this._getByKeyHost(key, optional, providerVisibility, lowerBoundVisibility);
} else {
return this._getByKeyDefault(key, optional, bindingVisibility, lowerBoundVisibility);
return this._getByKeyDefault(key, optional, providerVisibility, lowerBoundVisibility);
}
}
@ -914,18 +920,18 @@ export class Injector {
if (optional) {
return null;
} else {
throw new NoBindingError(this, key);
throw new NoProviderError(this, key);
}
}
/** @internal */
_getByKeySelf(key: Key, optional: boolean, bindingVisibility: Visibility): any {
var obj = this._strategy.getObjByKeyId(key.id, bindingVisibility);
_getByKeySelf(key: Key, optional: boolean, providerVisibility: Visibility): any {
var obj = this._strategy.getObjByKeyId(key.id, providerVisibility);
return (obj !== UNDEFINED) ? obj : this._throwOrNull(key, optional);
}
/** @internal */
_getByKeyHost(key: Key, optional: boolean, bindingVisibility: Visibility,
_getByKeyHost(key: Key, optional: boolean, providerVisibility: Visibility,
lowerBoundVisibility: Object): any {
var inj = this;
@ -938,7 +944,7 @@ export class Injector {
}
while (inj != null) {
var obj = inj._strategy.getObjByKeyId(key.id, bindingVisibility);
var obj = inj._strategy.getObjByKeyId(key.id, providerVisibility);
if (obj !== UNDEFINED) return obj;
if (isPresent(inj._parent) && inj._isHost) {
@ -958,20 +964,20 @@ export class Injector {
}
/** @internal */
_getByKeyDefault(key: Key, optional: boolean, bindingVisibility: Visibility,
_getByKeyDefault(key: Key, optional: boolean, providerVisibility: Visibility,
lowerBoundVisibility: Object): any {
var inj = this;
if (lowerBoundVisibility instanceof SkipSelfMetadata) {
bindingVisibility = inj._isHost ? Visibility.PublicAndPrivate : Visibility.Public;
providerVisibility = inj._isHost ? Visibility.PublicAndPrivate : Visibility.Public;
inj = inj._parent;
}
while (inj != null) {
var obj = inj._strategy.getObjByKeyId(key.id, bindingVisibility);
var obj = inj._strategy.getObjByKeyId(key.id, providerVisibility);
if (obj !== UNDEFINED) return obj;
bindingVisibility = inj._isHost ? Visibility.PublicAndPrivate : Visibility.Public;
providerVisibility = inj._isHost ? Visibility.PublicAndPrivate : Visibility.Public;
inj = inj._parent;
}
@ -979,7 +985,7 @@ export class Injector {
}
get displayName(): string {
return `Injector(bindings: [${_mapBindings(this, b => ` "${b.key.displayName}" `).join(", ")}])`;
return `Injector(providers: [${_mapProviders(this, b => ` "${b.key.displayName}" `).join(", ")}])`;
}
toString(): string { return this.displayName; }
@ -988,10 +994,10 @@ export class Injector {
var INJECTOR_KEY = Key.get(Injector);
function _mapBindings(injector: Injector, fn: Function): any[] {
function _mapProviders(injector: Injector, fn: Function): any[] {
var res = [];
for (var i = 0; i < injector._proto.numberOfBindings; ++i) {
res.push(fn(injector._proto.getBindingAtIndex(i)));
for (var i = 0; i < injector._proto.numberOfProviders; ++i) {
res.push(fn(injector._proto.getProviderAtIndex(i)));
}
return res;
}

View File

@ -16,7 +16,7 @@ export {TypeLiteral} from './type_literal';
* injector to store created objects in a more efficient way.
*
* `Key` should not be created directly. {@link Injector} creates keys automatically when resolving
* bindings.
* providers.
*/
export class Key {
/**

View File

@ -17,7 +17,7 @@ import {CONST, CONST_EXPR, stringify, isBlank, isPresent} from "angular2/src/cor
* }
*
* var injector = Injector.resolveAndCreate([
* bind("MyEngine").toClass(Engine),
* provide("MyEngine", {asClass: Engine}),
* Car
* ]);
*
@ -212,7 +212,7 @@ export class SkipSelfMetadata {
*
* @Component({
* selector: 'parent-cmp',
* bindings: [HostService]
* providers: [HostService]
* })
* @View({
* template: `
@ -225,7 +225,7 @@ export class SkipSelfMetadata {
*
* @Component({
* selector: 'app',
* bindings: [OtherService]
* providers: [OtherService]
* })
* @View({
* template: `

View File

@ -1,22 +1,22 @@
import {CONST} from 'angular2/src/core/facade/lang';
/**
* Creates a token that can be used in a DI Binding.
* Creates a token that can be used in a DI Provider.
*
* ### Example ([live demo](http://plnkr.co/edit/Ys9ezXpj2Mnoy3Uc8KBp?p=preview))
*
* ```typescript
* var t = new OpaqueToken("binding");
* var t = new OpaqueToken("value");
*
* var injector = Injector.resolveAndCreate([
* bind(t).toValue("bindingValue")
* provide(t, {asValue: "providedValue"})
* ]);
*
* expect(injector.get(t)).toEqual("bindingValue");
* ```
*
* Using an `OpaqueToken` is preferable to using strings as tokens because of possible collisions
* caused by multiple bindings using the same string as two different tokens.
* caused by multiple providers using the same string as two different tokens.
*
* Using an `OpaqueToken` is preferable to using an `Object` as tokens because it provides better
* error messages.

View File

@ -25,8 +25,8 @@ import {
} from './metadata';
import {
NoAnnotationError,
MixingMultiBindingsWithRegularBindings,
InvalidBindingError
MixingMultiProvidersWithRegularProvidersError,
InvalidProviderError
} from './exceptions';
import {resolveForwardRef} from './forward_ref';
@ -42,22 +42,22 @@ const _EMPTY_LIST = CONST_EXPR([]);
/**
* Describes how the {@link Injector} should instantiate a given token.
*
* See {@link bind}.
* See {@link provide}.
*
* ### Example ([live demo](http://plnkr.co/edit/GNAyj6K6PfYg2NBzgwZ5?p%3Dpreview&p=preview))
*
* ```javascript
* var injector = Injector.resolveAndCreate([
* new Binding("message", { toValue: 'Hello' })
* new Provider("message", { toValue: 'Hello' })
* ]);
*
* expect(injector.get("message")).toEqual('Hello');
* ```
*/
@CONST()
export class Binding {
export class Provider {
/**
* Token used when retrieving this binding. Usually, it is a type {@link `Type`}.
* Token used when retrieving this provider. Usually, it is a type {@link `Type`}.
*/
token;
@ -77,11 +77,11 @@ export class Binding {
*
* var injectorClass = Injector.resolveAndCreate([
* Car,
* new Binding(Vehicle, { toClass: Car })
* new Provider(Vehicle, { toClass: Car })
* ]);
* var injectorAlias = Injector.resolveAndCreate([
* Car,
* new Binding(Vehicle, { toAlias: Car })
* new Provider(Vehicle, { toAlias: Car })
* ]);
*
* expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
@ -100,7 +100,7 @@ export class Binding {
*
* ```javascript
* var injector = Injector.resolveAndCreate([
* new Binding("message", { toValue: 'Hello' })
* new Provider("message", { toValue: 'Hello' })
* ]);
*
* expect(injector.get("message")).toEqual('Hello');
@ -126,11 +126,11 @@ export class Binding {
*
* var injectorAlias = Injector.resolveAndCreate([
* Car,
* new Binding(Vehicle, { toAlias: Car })
* new Provider(Vehicle, { toAlias: Car })
* ]);
* var injectorClass = Injector.resolveAndCreate([
* Car,
* new Binding(Vehicle, { toClass: Car })
* new Provider(Vehicle, { toClass: Car })
* ]);
*
* expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
@ -149,8 +149,8 @@ export class Binding {
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* new Binding(Number, { toFactory: () => { return 1+2; }}),
* new Binding(String, { toFactory: (value) => { return "Value: " + value; },
* new Provider(Number, { toFactory: () => { return 1+2; }}),
* new Provider(String, { toFactory: (value) => { return "Value: " + value; },
* deps: [Number] })
* ]);
*
@ -170,8 +170,8 @@ export class Binding {
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* new Binding(Number, { toFactory: () => { return 1+2; }}),
* new Binding(String, { toFactory: (value) => { return "Value: " + value; },
* new Provider(Number, { toFactory: () => { return 1+2; }}),
* new Provider(String, { toFactory: (value) => { return "Value: " + value; },
* deps: [Number] })
* ]);
*
@ -205,40 +205,63 @@ export class Binding {
// TODO: Provide a full working example after alpha38 is released.
/**
* Creates multiple bindings matching the same token (a multi-binding).
* Creates multiple providers matching the same token (a multi-provider).
*
* Multi-bindings are used for creating pluggable service, where the system comes
* with some default bindings, and the user can register additonal bindings.
* The combination of the default bindings and the additional bindings will be
* Multi-providers are used for creating pluggable service, where the system comes
* with some default providers, and the user can register additonal providers.
* The combination of the default providers and the additional providers will be
* used to drive the behavior of the system.
*
* ### Example
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* new Binding("Strings", { toValue: "String1", multi: true}),
* new Binding("Strings", { toValue: "String2", multi: true})
* new Provider("Strings", { toValue: "String1", multi: true}),
* new Provider("Strings", { toValue: "String2", multi: true})
* ]);
*
* expect(injector.get("Strings")).toEqual(["String1", "String2"]);
* ```
*
* Multi-bindings and regular bindings cannot be mixed. The following
* Multi-providers and regular providers cannot be mixed. The following
* will throw an exception:
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* new Binding("Strings", { toValue: "String1", multi: true }),
* new Binding("Strings", { toValue: "String2"})
* new Provider("Strings", { toValue: "String1", multi: true }),
* new Provider("Strings", { toValue: "String2"})
* ]);
* ```
*/
get multi(): boolean { return normalizeBool(this._multi); }
}
/**
* @deprecated
*/
@CONST()
export class Binding extends Provider {
constructor(token, {toClass, toValue, toAlias, toFactory, deps, multi}: {
toClass?: Type,
toValue?: any,
toAlias?: any,
toFactory?: Function,
deps?: Object[],
multi?: boolean
}) {
super(token, {
toClass: toClass,
toValue: toValue,
toAlias: toAlias,
toFactory: toFactory,
deps: deps,
multi: multi
});
}
}
/**
* An internal resolved representation of a {@link Binding} used by the {@link Injector}.
* An internal resolved representation of a {@link Provider} used by the {@link Injector}.
*
* It is usually created automatically by `Injector.resolveAndCreate`.
*
@ -247,13 +270,13 @@ export class Binding {
* ### Example ([live demo](http://plnkr.co/edit/RfEnhh8kUEI0G3qsnIeT?p%3Dpreview&p=preview))
*
* ```typescript
* var resolvedBindings = Injector.resolve([new Binding('message', {toValue: 'Hello'})]);
* var injector = Injector.fromResolvedBindings(resolvedBindings);
* var resolvedProviders = Injector.resolve([new Provider('message', {toValue: 'Hello'})]);
* var injector = Injector.fromResolvedProviders(resolvedProviders);
*
* expect(injector.get('message')).toEqual('Hello');
* ```
*/
export interface ResolvedBinding {
export interface ResolvedProvider {
/**
* A key, usually a `Type`.
*/
@ -265,20 +288,25 @@ export interface ResolvedBinding {
resolvedFactories: ResolvedFactory[];
/**
* Indicates if the binding is a multi-binding or a regular binding.
* Indicates if the provider is a multi-provider or a regular provider.
*/
multiBinding: boolean;
multiProvider: boolean;
}
export class ResolvedBinding_ implements ResolvedBinding {
/**
* @deprecated
*/
export interface ResolvedBinding extends ResolvedProvider {}
export class ResolvedProvider_ implements ResolvedBinding {
constructor(public key: Key, public resolvedFactories: ResolvedFactory[],
public multiBinding: boolean) {}
public multiProvider: boolean) {}
get resolvedFactory(): ResolvedFactory { return this.resolvedFactories[0]; }
}
/**
* An internal resolved representation of a factory function created by resolving {@link Binding}.
* An internal resolved representation of a factory function created by resolving {@link Provider}.
*/
export class ResolvedFactory {
constructor(
@ -294,22 +322,49 @@ export class ResolvedFactory {
}
/**
* Creates a {@link Binding}.
* @deprecated
* Creates a {@link Provider}.
*
* To construct a {@link Binding}, bind a `token` to either a class, a value, a factory function, or
* To construct a {@link Provider}, bind a `token` to either a class, a value, a factory function,
* or
* to an alias to another `token`.
* See {@link BindingBuilder} for more details.
* See {@link ProviderBuilder} for more details.
*
* The `token` is most commonly a class or {@link angular2/di/OpaqueToken}.
*/
export function bind(token): BindingBuilder {
return new BindingBuilder(token);
export function bind(token): ProviderBuilder {
return new ProviderBuilder(token);
}
/**
* Creates a {@link Provider}.
*
* See {@link Provider} for more details.
*
* <!-- TODO: improve the docs -->
*/
export function provide(token, {asClass, asValue, asAlias, asFactory, deps, multi}: {
asClass?: Type,
asValue?: any,
asAlias?: any,
asFactory?: Function,
deps?: Object[],
multi?: boolean
}): Provider {
return new Provider(token, {
toClass: asClass,
toValue: asValue,
toAlias: asAlias,
toFactory: asFactory,
deps: deps,
multi: multi
});
}
/**
* Helper class for the {@link bind} function.
*/
export class BindingBuilder {
export class ProviderBuilder {
constructor(public token) {}
/**
@ -327,11 +382,11 @@ export class BindingBuilder {
*
* var injectorClass = Injector.resolveAndCreate([
* Car,
* bind(Vehicle).toClass(Car)
* provide(Vehicle, {asClass: Car})
* ]);
* var injectorAlias = Injector.resolveAndCreate([
* Car,
* bind(Vehicle).toAlias(Car)
* provide(Vehicle, {asAlias: Car})
* ]);
*
* expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
@ -341,12 +396,12 @@ export class BindingBuilder {
* expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);
* ```
*/
toClass(type: Type): Binding {
toClass(type: Type): Provider {
if (!isType(type)) {
throw new BaseException(
`Trying to create a class binding but "${stringify(type)}" is not a class!`);
`Trying to create a class provider but "${stringify(type)}" is not a class!`);
}
return new Binding(this.token, {toClass: type});
return new Provider(this.token, {toClass: type});
}
/**
@ -356,13 +411,13 @@ export class BindingBuilder {
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* bind('message').toValue('Hello')
* provide('message', {asValue: 'Hello'})
* ]);
*
* expect(injector.get('message')).toEqual('Hello');
* ```
*/
toValue(value: any): Binding { return new Binding(this.token, {toValue: value}); }
toValue(value: any): Provider { return new Provider(this.token, {toValue: value}); }
/**
* Binds a DI token as an alias for an existing token.
@ -383,11 +438,11 @@ export class BindingBuilder {
*
* var injectorAlias = Injector.resolveAndCreate([
* Car,
* bind(Vehicle).toAlias(Car)
* provide(Vehicle, {asAlias: Car})
* ]);
* var injectorClass = Injector.resolveAndCreate([
* Car,
* bind(Vehicle).toClass(Car)
* provide(Vehicle, {asClass: Car})
* ]);
*
* expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
@ -397,11 +452,11 @@ export class BindingBuilder {
* expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);
* ```
*/
toAlias(aliasToken: /*Type*/ any): Binding {
toAlias(aliasToken: /*Type*/ any): Provider {
if (isBlank(aliasToken)) {
throw new BaseException(`Can not alias ${stringify(this.token)} to a blank value!`);
}
return new Binding(this.token, {toAlias: aliasToken});
return new Provider(this.token, {toAlias: aliasToken});
}
/**
@ -411,69 +466,69 @@ export class BindingBuilder {
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* bind(Number).toFactory(() => { return 1+2; }),
* bind(String).toFactory((v) => { return "Value: " + v; }, [Number])
* provide(Number, {asFactory: () => { return 1+2; }}),
* provide(String, {asFactory: (v) => { return "Value: " + v; }, deps: [Number]})
* ]);
*
* expect(injector.get(Number)).toEqual(3);
* expect(injector.get(String)).toEqual('Value: 3');
* ```
*/
toFactory(factory: Function, dependencies?: any[]): Binding {
toFactory(factory: Function, dependencies?: any[]): Provider {
if (!isFunction(factory)) {
throw new BaseException(
`Trying to create a factory binding but "${stringify(factory)}" is not a function!`);
`Trying to create a factory provider but "${stringify(factory)}" is not a function!`);
}
return new Binding(this.token, {toFactory: factory, deps: dependencies});
return new Provider(this.token, {toFactory: factory, deps: dependencies});
}
}
/**
* Resolve a single binding.
* Resolve a single provider.
*/
export function resolveFactory(binding: Binding): ResolvedFactory {
export function resolveFactory(provider: Provider): ResolvedFactory {
var factoryFn: Function;
var resolvedDeps;
if (isPresent(binding.toClass)) {
var toClass = resolveForwardRef(binding.toClass);
if (isPresent(provider.toClass)) {
var toClass = resolveForwardRef(provider.toClass);
factoryFn = reflector.factory(toClass);
resolvedDeps = _dependenciesFor(toClass);
} else if (isPresent(binding.toAlias)) {
} else if (isPresent(provider.toAlias)) {
factoryFn = (aliasInstance) => aliasInstance;
resolvedDeps = [Dependency.fromKey(Key.get(binding.toAlias))];
} else if (isPresent(binding.toFactory)) {
factoryFn = binding.toFactory;
resolvedDeps = _constructDependencies(binding.toFactory, binding.dependencies);
resolvedDeps = [Dependency.fromKey(Key.get(provider.toAlias))];
} else if (isPresent(provider.toFactory)) {
factoryFn = provider.toFactory;
resolvedDeps = _constructDependencies(provider.toFactory, provider.dependencies);
} else {
factoryFn = () => binding.toValue;
factoryFn = () => provider.toValue;
resolvedDeps = _EMPTY_LIST;
}
return new ResolvedFactory(factoryFn, resolvedDeps);
}
/**
* Converts the {@link Binding} into {@link ResolvedBinding}.
* Converts the {@link Provider} into {@link ResolvedProvider}.
*
* {@link Injector} internally only uses {@link ResolvedBinding}, {@link Binding} contains
* convenience binding syntax.
* {@link Injector} internally only uses {@link ResolvedProvider}, {@link Provider} contains
* convenience provider syntax.
*/
export function resolveBinding(binding: Binding): ResolvedBinding {
return new ResolvedBinding_(Key.get(binding.token), [resolveFactory(binding)], false);
export function resolveProvider(provider: Provider): ResolvedProvider {
return new ResolvedProvider_(Key.get(provider.token), [resolveFactory(provider)], false);
}
/**
* Resolve a list of Bindings.
* Resolve a list of Providers.
*/
export function resolveBindings(bindings: Array<Type | Binding | any[]>): ResolvedBinding[] {
var normalized = _createListOfBindings(
_normalizeBindings(bindings, new Map<number, _NormalizedBinding | _NormalizedBinding[]>()));
export function resolveProviders(providers: Array<Type | Provider | any[]>): ResolvedProvider[] {
var normalized = _createListOfProviders(_normalizeProviders(
providers, new Map<number, _NormalizedProvider | _NormalizedProvider[]>()));
return normalized.map(b => {
if (b instanceof _NormalizedBinding) {
return new ResolvedBinding_(b.key, [b.resolvedFactory], false);
if (b instanceof _NormalizedProvider) {
return new ResolvedProvider_(b.key, [b.resolvedFactory], false);
} else {
var arr = <_NormalizedBinding[]>b;
return new ResolvedBinding_(arr[0].key, arr.map(_ => _.resolvedFactory), true);
var arr = <_NormalizedProvider[]>b;
return new ResolvedProvider_(arr[0].key, arr.map(_ => _.resolvedFactory), true);
}
});
}
@ -481,66 +536,66 @@ export function resolveBindings(bindings: Array<Type | Binding | any[]>): Resolv
/**
* The algorithm works as follows:
*
* [Binding] -> [_NormalizedBinding|[_NormalizedBinding]] -> [ResolvedBinding]
* [Provider] -> [_NormalizedProvider|[_NormalizedProvider]] -> [ResolvedProvider]
*
* _NormalizedBinding is essentially a resolved binding before it was grouped by key.
* _NormalizedProvider is essentially a resolved provider before it was grouped by key.
*/
class _NormalizedBinding {
class _NormalizedProvider {
constructor(public key: Key, public resolvedFactory: ResolvedFactory) {}
}
function _createListOfBindings(flattenedBindings: Map<number, any>): any[] {
return MapWrapper.values(flattenedBindings);
function _createListOfProviders(flattenedProviders: Map<number, any>): any[] {
return MapWrapper.values(flattenedProviders);
}
function _normalizeBindings(bindings: Array<Type | Binding | BindingBuilder | any[]>,
res: Map<number, _NormalizedBinding | _NormalizedBinding[]>):
Map<number, _NormalizedBinding | _NormalizedBinding[]> {
bindings.forEach(b => {
function _normalizeProviders(providers: Array<Type | Provider | ProviderBuilder | any[]>,
res: Map<number, _NormalizedProvider | _NormalizedProvider[]>):
Map<number, _NormalizedProvider | _NormalizedProvider[]> {
providers.forEach(b => {
if (b instanceof Type) {
_normalizeBinding(bind(b).toClass(b), res);
_normalizeProvider(provide(b, {asClass: b}), res);
} else if (b instanceof Binding) {
_normalizeBinding(b, res);
} else if (b instanceof Provider) {
_normalizeProvider(b, res);
} else if (b instanceof Array) {
_normalizeBindings(b, res);
_normalizeProviders(b, res);
} else if (b instanceof BindingBuilder) {
throw new InvalidBindingError(b.token);
} else if (b instanceof ProviderBuilder) {
throw new InvalidProviderError(b.token);
} else {
throw new InvalidBindingError(b);
throw new InvalidProviderError(b);
}
});
return res;
}
function _normalizeBinding(b: Binding, res: Map<number, _NormalizedBinding | _NormalizedBinding[]>):
void {
function _normalizeProvider(b: Provider,
res: Map<number, _NormalizedProvider | _NormalizedProvider[]>): void {
var key = Key.get(b.token);
var factory = resolveFactory(b);
var normalized = new _NormalizedBinding(key, factory);
var normalized = new _NormalizedProvider(key, factory);
if (b.multi) {
var existingBinding = res.get(key.id);
var existingProvider = res.get(key.id);
if (existingBinding instanceof Array) {
existingBinding.push(normalized);
if (existingProvider instanceof Array) {
existingProvider.push(normalized);
} else if (isBlank(existingBinding)) {
} else if (isBlank(existingProvider)) {
res.set(key.id, [normalized]);
} else {
throw new MixingMultiBindingsWithRegularBindings(existingBinding, b);
throw new MixingMultiProvidersWithRegularProvidersError(existingProvider, b);
}
} else {
var existingBinding = res.get(key.id);
var existingProvider = res.get(key.id);
if (existingBinding instanceof Array) {
throw new MixingMultiBindingsWithRegularBindings(existingBinding, b);
if (existingProvider instanceof Array) {
throw new MixingMultiProvidersWithRegularProvidersError(existingProvider, b);
}
res.set(key.id, normalized);

View File

@ -27,7 +27,7 @@ class _ArrayLogger {
* }
* }
*
* bootstrap(MyApp, [bind(ExceptionHandler).toClass(MyExceptionHandler)])
* bootstrap(MyApp, [provide(ExceptionHandler, {asClass: MyExceptionHandler})])
*
* ```
*/

View File

@ -41,12 +41,17 @@ import {FormBuilder} from './forms/form_builder';
import {CONST_EXPR, Type} from './facade/lang';
/**
* Shorthand set of bindings used for building Angular forms.
* Shorthand set of providers used for building Angular forms.
*
* ### Example:
*
* ```typescript
* bootstrap(MyApp, [FORM_BINDINGS]);
* bootstrap(MyApp, [FORM_PROVIDERS]);
* ```
*/
export const FORM_BINDINGS: Type[] = CONST_EXPR([FormBuilder]);
export const FORM_PROVIDERS: Type[] = CONST_EXPR([FormBuilder]);
/**
* @deprecated
*/
export const FORM_BINDINGS = FORM_PROVIDERS;

View File

@ -1,13 +1,13 @@
import {Directive} from 'angular2/src/core/metadata';
import {Renderer} from 'angular2/src/core/render';
import {ElementRef} from 'angular2/src/core/linker';
import {Self, forwardRef, Binding} from 'angular2/src/core/di';
import {Self, forwardRef, Provider} from 'angular2/src/core/di';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor';
import {CONST_EXPR} from 'angular2/src/core/facade/lang';
import {setProperty} from './shared';
const CHECKBOX_VALUE_ACCESSOR = CONST_EXPR(new Binding(
const CHECKBOX_VALUE_ACCESSOR = CONST_EXPR(new Provider(
NG_VALUE_ACCESSOR, {toAlias: forwardRef(() => CheckboxControlValueAccessor), multi: true}));
/**

View File

@ -1,13 +1,13 @@
import {Directive} from 'angular2/src/core/metadata';
import {ElementRef} from 'angular2/src/core/linker';
import {Renderer} from 'angular2/src/core/render';
import {Self, forwardRef, Binding} from 'angular2/src/core/di';
import {Self, forwardRef, Provider} from 'angular2/src/core/di';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor';
import {isBlank, CONST_EXPR} from 'angular2/src/core/facade/lang';
import {setProperty} from './shared';
const DEFAULT_VALUE_ACCESSOR = CONST_EXPR(
new Binding(NG_VALUE_ACCESSOR, {toAlias: forwardRef(() => DefaultValueAccessor), multi: true}));
const DEFAULT_VALUE_ACCESSOR = CONST_EXPR(new Provider(
NG_VALUE_ACCESSOR, {toAlias: forwardRef(() => DefaultValueAccessor), multi: true}));
/**
* The default accessor for writing a value and listening to changes that is used by the

View File

@ -1,6 +1,6 @@
import {OnInit, OnDestroy} from 'angular2/lifecycle_hooks';
import {Directive} from 'angular2/src/core/metadata';
import {Inject, Host, SkipSelf, forwardRef, Binding} from 'angular2/src/core/di';
import {Inject, Host, SkipSelf, forwardRef, Provider} from 'angular2/src/core/di';
import {ListWrapper} from 'angular2/src/core/facade/collection';
import {CONST_EXPR} from 'angular2/src/core/facade/lang';
@ -10,7 +10,7 @@ import {ControlGroup} from '../model';
import {Form} from './form_interface';
const controlGroupBinding =
CONST_EXPR(new Binding(ControlContainer, {toAlias: forwardRef(() => NgControlGroup)}));
CONST_EXPR(new Provider(ControlContainer, {toAlias: forwardRef(() => NgControlGroup)}));
/**
* Creates and binds a control group to a DOM element.

View File

@ -3,7 +3,7 @@ import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async';
import {OnChanges, OnDestroy} from 'angular2/lifecycle_hooks';
import {SimpleChange} from 'angular2/src/core/change_detection';
import {Query, Directive} from 'angular2/src/core/metadata';
import {forwardRef, Host, SkipSelf, Binding, Inject, Optional} from 'angular2/src/core/di';
import {forwardRef, Host, SkipSelf, Provider, Inject, Optional} from 'angular2/src/core/di';
import {ControlContainer} from './control_container';
import {NgControl} from './ng_control';
@ -14,7 +14,7 @@ import {Validators, NG_VALIDATORS} from '../validators';
const controlNameBinding =
CONST_EXPR(new Binding(NgControl, {toAlias: forwardRef(() => NgControlName)}));
CONST_EXPR(new Provider(NgControl, {toAlias: forwardRef(() => NgControlName)}));
/**
* Creates and binds a control with a specified name to a DOM element.

View File

@ -7,7 +7,7 @@ import {
import {StringMapWrapper, ListWrapper} from 'angular2/src/core/facade/collection';
import {isPresent, isBlank, CONST_EXPR} from 'angular2/src/core/facade/lang';
import {Directive} from 'angular2/src/core/metadata';
import {forwardRef, Binding} from 'angular2/src/core/di';
import {forwardRef, Provider} from 'angular2/src/core/di';
import {NgControl} from './ng_control';
import {Form} from './form_interface';
import {NgControlGroup} from './ng_control_group';
@ -15,8 +15,8 @@ import {ControlContainer} from './control_container';
import {AbstractControl, ControlGroup, Control} from '../model';
import {setUpControl} from './shared';
const formDirectiveBinding =
CONST_EXPR(new Binding(ControlContainer, {toAlias: forwardRef(() => NgForm)}));
const formDirectiveProvider =
CONST_EXPR(new Provider(ControlContainer, {toAlias: forwardRef(() => NgForm)}));
/**
* If `NgForm` is bound in a component, `<form>` elements in that component will be
@ -81,7 +81,7 @@ const formDirectiveBinding =
*/
@Directive({
selector: 'form:not([ng-no-form]):not([ng-form-model]),ng-form,[ng-form]',
bindings: [formDirectiveBinding],
bindings: [formDirectiveProvider],
host: {
'(submit)': 'onSubmit()',
},

View File

@ -3,7 +3,7 @@ import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async';
import {OnChanges} from 'angular2/lifecycle_hooks';
import {SimpleChange} from 'angular2/src/core/change_detection';
import {Query, Directive} from 'angular2/src/core/metadata';
import {forwardRef, Binding, Inject, Optional} from 'angular2/src/core/di';
import {forwardRef, Provider, Inject, Optional} from 'angular2/src/core/di';
import {NgControl} from './ng_control';
import {Control} from '../model';
import {Validators, NG_VALIDATORS} from '../validators';
@ -11,7 +11,7 @@ import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor'
import {setUpControl, isPropertyUpdated, selectValueAccessor} from './shared';
const formControlBinding =
CONST_EXPR(new Binding(NgControl, {toAlias: forwardRef(() => NgFormControl)}));
CONST_EXPR(new Provider(NgControl, {toAlias: forwardRef(() => NgFormControl)}));
/**
* Binds an existing {@link Control} to a DOM element.

View File

@ -4,7 +4,7 @@ import {ObservableWrapper, EventEmitter} from 'angular2/src/core/facade/async';
import {OnChanges} from 'angular2/lifecycle_hooks';
import {Directive} from 'angular2/src/core/metadata';
import {forwardRef, Binding} from 'angular2/src/core/di';
import {forwardRef, Provider} from 'angular2/src/core/di';
import {NgControl} from './ng_control';
import {NgControlGroup} from './ng_control_group';
import {ControlContainer} from './control_container';
@ -12,8 +12,8 @@ import {Form} from './form_interface';
import {Control, ControlGroup} from '../model';
import {setUpControl} from './shared';
const formDirectiveBinding =
CONST_EXPR(new Binding(ControlContainer, {toAlias: forwardRef(() => NgFormModel)}));
const formDirectiveProvider =
CONST_EXPR(new Provider(ControlContainer, {toAlias: forwardRef(() => NgFormModel)}));
/**
* Binds an existing control group to a DOM element.
@ -91,7 +91,7 @@ const formDirectiveBinding =
*/
@Directive({
selector: '[ng-form-model]',
bindings: [formDirectiveBinding],
bindings: [formDirectiveProvider],
inputs: ['form: ng-form-model'],
host: {'(submit)': 'onSubmit()'},
outputs: ['ngSubmit'],

View File

@ -3,14 +3,15 @@ import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async';
import {OnChanges} from 'angular2/lifecycle_hooks';
import {SimpleChange} from 'angular2/src/core/change_detection';
import {Query, Directive} from 'angular2/src/core/metadata';
import {forwardRef, Binding, Inject, Optional} from 'angular2/src/core/di';
import {forwardRef, Provider, Inject, Optional} from 'angular2/src/core/di';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
import {NgControl} from './ng_control';
import {Control} from '../model';
import {Validators, NG_VALIDATORS} from '../validators';
import {setUpControl, isPropertyUpdated, selectValueAccessor} from './shared';
const formControlBinding = CONST_EXPR(new Binding(NgControl, {toAlias: forwardRef(() => NgModel)}));
const formControlBinding =
CONST_EXPR(new Provider(NgControl, {toAlias: forwardRef(() => NgModel)}));
/**
* Binds a domain model to a form control.

View File

@ -1,4 +1,4 @@
import {Self, forwardRef, Binding} from 'angular2/src/core/di';
import {Self, forwardRef, Provider} from 'angular2/src/core/di';
import {Renderer} from 'angular2/src/core/render';
import {ElementRef, QueryList} from 'angular2/src/core/linker';
import {Query, Directive} from 'angular2/src/core/metadata';
@ -8,7 +8,7 @@ import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor'
import {CONST_EXPR} from 'angular2/src/core/facade/lang';
import {setProperty} from './shared';
const SELECT_VALUE_ACCESSOR = CONST_EXPR(new Binding(
const SELECT_VALUE_ACCESSOR = CONST_EXPR(new Provider(
NG_VALUE_ACCESSOR, {toAlias: forwardRef(() => SelectControlValueAccessor), multi: true}));
/**

View File

@ -1,10 +1,10 @@
import {forwardRef, Binding, OpaqueToken} from 'angular2/src/core/di';
import {forwardRef, Provider, OpaqueToken} from 'angular2/src/core/di';
import {CONST_EXPR} from 'angular2/src/core/facade/lang';
import {Directive} from 'angular2/src/core/metadata';
import {Validators, NG_VALIDATORS} from '../validators';
const DEFAULT_VALIDATORS =
CONST_EXPR(new Binding(NG_VALIDATORS, {toValue: Validators.required, multi: true}));
CONST_EXPR(new Provider(NG_VALIDATORS, {toValue: Validators.required, multi: true}));
@Directive({
selector: '[required][ng-control],[required][ng-form-control],[required][ng-model]',

View File

@ -15,7 +15,7 @@ import * as modelModule from './model';
*
* @Component({
* selector: 'login-comp',
* viewBindings: [FormBuilder]
* viewProviders: [FormBuilder]
* })
* @View({
* template: `

View File

@ -108,22 +108,18 @@ export class DirectiveResolver {
var mergedQueries =
isPresent(dm.queries) ? StringMapWrapper.merge(dm.queries, queries) : queries;
// TODO: remove after migrating from properties to inputs
if (mergedInputs.length == 0 && isPresent(dm.properties)) mergedInputs = dm.properties;
if (mergedOutputs.length == 0 && isPresent(dm.events)) mergedOutputs = dm.events;
if (dm instanceof ComponentMetadata) {
return new ComponentMetadata({
selector: dm.selector,
inputs: mergedInputs,
outputs: mergedOutputs,
host: mergedHost,
bindings: dm.bindings,
exportAs: dm.exportAs,
moduleId: dm.moduleId,
queries: mergedQueries,
changeDetection: dm.changeDetection,
viewBindings: dm.viewBindings
providers: dm.providers,
viewProviders: dm.viewProviders
});
} else {
@ -132,10 +128,10 @@ export class DirectiveResolver {
inputs: mergedInputs,
outputs: mergedOutputs,
host: mergedHost,
bindings: dm.bindings,
exportAs: dm.exportAs,
moduleId: dm.moduleId,
queries: mergedQueries
queries: mergedQueries,
providers: dm.providers
});
}
}

View File

@ -1,4 +1,4 @@
import {Key, Injector, ResolvedBinding, Binding, bind, Injectable} from 'angular2/src/core/di';
import {Key, Injector, ResolvedProvider, Provider, provide, Injectable} from 'angular2/src/core/di';
import {Compiler} from './compiler';
import {isType, Type, stringify, isPresent} from 'angular2/src/core/facade/lang';
import {Promise} from 'angular2/src/core/facade/async';
@ -161,7 +161,7 @@ export abstract class DynamicComponentLoader {
* location within the Component View of this Component Instance is specified via `anchorName`
* Template Variable Name.
*
* You can optionally provide `bindings` to configure the {@link Injector} provisioned for this
* You can optionally provide `providers` to configure the {@link Injector} provisioned for this
* Component Instance.
*
* Returns a promise for the {@link ComponentRef} representing the newly created Component.
@ -209,13 +209,13 @@ export abstract class DynamicComponentLoader {
* ```
*/
abstract loadIntoLocation(type: Type, hostLocation: ElementRef, anchorName: string,
bindings?: ResolvedBinding[]): Promise<ComponentRef>;
providers?: ResolvedProvider[]): Promise<ComponentRef>;
/**
* Creates an instance of a Component and attaches it to the View Container found at the
* `location` specified as {@link ElementRef}.
*
* You can optionally provide `bindings` to configure the {@link Injector} provisioned for this
* You can optionally provide `providers` to configure the {@link Injector} provisioned for this
* Component Instance.
*
* Returns a promise for the {@link ComponentRef} representing the newly created Component.
@ -256,7 +256,7 @@ export abstract class DynamicComponentLoader {
* <child-component>Child</child-component>
* ```
*/
abstract loadNextToLocation(type: Type, location: ElementRef, bindings?: ResolvedBinding[]):
abstract loadNextToLocation(type: Type, location: ElementRef, providers?: ResolvedProvider[]):
Promise<ComponentRef>;
}
@ -283,17 +283,18 @@ export class DynamicComponentLoader_ extends DynamicComponentLoader {
}
loadIntoLocation(type: Type, hostLocation: ElementRef, anchorName: string,
bindings: ResolvedBinding[] = null): Promise<ComponentRef> {
providers: ResolvedProvider[] = null): Promise<ComponentRef> {
return this.loadNextToLocation(
type, this._viewManager.getNamedElementInComponentView(hostLocation, anchorName), bindings);
type, this._viewManager.getNamedElementInComponentView(hostLocation, anchorName),
providers);
}
loadNextToLocation(type: Type, location: ElementRef,
bindings: ResolvedBinding[] = null): Promise<ComponentRef> {
providers: ResolvedProvider[] = null): Promise<ComponentRef> {
return this._compiler.compileInHost(type).then(hostProtoViewRef => {
var viewContainer = this._viewManager.getViewContainer(location);
var hostViewRef =
viewContainer.createHostView(hostProtoViewRef, viewContainer.length, bindings);
viewContainer.createHostView(hostProtoViewRef, viewContainer.length, providers);
var newLocation = this._viewManager.getHostElement(hostViewRef);
var component = this._viewManager.getComponent(newLocation);

View File

@ -1,13 +1,13 @@
import {isBlank} from 'angular2/src/core/facade/lang';
import {BaseException} from 'angular2/src/core/facade/exceptions';
import * as eiModule from './element_injector';
import {DirectiveBinding} from './element_injector';
import {DirectiveProvider} from './element_injector';
import * as viewModule from './view';
export class ElementBinder {
constructor(public index: number, public parent: ElementBinder, public distanceToParent: number,
public protoElementInjector: eiModule.ProtoElementInjector,
public componentDirective: DirectiveBinding,
public componentDirective: DirectiveProvider,
public nestedProtoView: viewModule.AppProtoView) {
if (isBlank(index)) {
throw new BaseException('null index not allowed.');

View File

@ -13,11 +13,11 @@ import {
Injector,
Key,
Dependency,
bind,
Binding,
ResolvedBinding,
NoBindingError,
AbstractBindingError,
provide,
Provider,
ResolvedProvider,
NoProviderError,
AbstractProviderError,
CyclicDependencyError,
resolveForwardRef
} from 'angular2/src/core/di';
@ -27,10 +27,10 @@ import {
Visibility,
InjectorInlineStrategy,
InjectorDynamicStrategy,
BindingWithVisibility,
ProviderWithVisibility,
DependencyProvider
} from 'angular2/src/core/di/injector';
import {resolveBinding, ResolvedFactory, ResolvedBinding_} from 'angular2/src/core/di/binding';
import {resolveProvider, ResolvedFactory, ResolvedProvider_} from 'angular2/src/core/di/provider';
import {AttributeMetadata, QueryMetadata} from '../metadata/di';
@ -49,7 +49,7 @@ import {QueryList} from './query_list';
import {reflector} from 'angular2/src/core/reflection/reflection';
import {SetterFn} from 'angular2/src/core/reflection/types';
import {EventConfig} from 'angular2/src/core/linker/event_config';
import {PipeBinding} from '../pipes/pipe_binding';
import {PipeProvider} from 'angular2/src/core/pipes/pipe_provider';
import {LifecycleHooks} from './interfaces';
import {ViewContainerRef_} from "./view_container_ref";
@ -129,12 +129,12 @@ export class DirectiveDependency extends Dependency {
}
}
export class DirectiveBinding extends ResolvedBinding_ {
export class DirectiveProvider extends ResolvedProvider_ {
public callOnDestroy: boolean;
constructor(key: Key, factory: Function, deps: Dependency[], public metadata: DirectiveMetadata,
public bindings: Array<Type | Binding | any[]>,
public viewBindings: Array<Type | Binding | any[]>) {
public providers: Array<Type | Provider | any[]>,
public viewProviders: Array<Type | Provider | any[]>) {
super(key, [new ResolvedFactory(factory, deps)], false);
this.callOnDestroy = hasLifecycleHook(LifecycleHooks.OnDestroy, key.token);
}
@ -157,24 +157,25 @@ export class DirectiveBinding extends ResolvedBinding_ {
[];
}
static createFromBinding(binding: Binding, meta: DirectiveMetadata): DirectiveBinding {
static createFromProvider(provider: Provider, meta: DirectiveMetadata): DirectiveProvider {
if (isBlank(meta)) {
meta = new DirectiveMetadata();
}
var rb = resolveBinding(binding);
var rb = resolveProvider(provider);
var rf = rb.resolvedFactories[0];
var deps = rf.dependencies.map(DirectiveDependency.createFrom);
var bindings = isPresent(meta.bindings) ? meta.bindings : [];
var viewBindigs =
meta instanceof ComponentMetadata && isPresent(meta.viewBindings) ? meta.viewBindings : [];
return new DirectiveBinding(rb.key, rf.factory, deps, meta, bindings, viewBindigs);
var providers = isPresent(meta.providers) ? meta.providers : [];
var viewBindigs = meta instanceof ComponentMetadata && isPresent(meta.viewProviders) ?
meta.viewProviders :
[];
return new DirectiveProvider(rb.key, rf.factory, deps, meta, providers, viewBindigs);
}
static createFromType(type: Type, annotation: DirectiveMetadata): DirectiveBinding {
var binding = new Binding(type, {toClass: type});
return DirectiveBinding.createFromBinding(binding, annotation);
static createFromType(type: Type, annotation: DirectiveMetadata): DirectiveProvider {
var provider = new Provider(type, {toClass: type});
return DirectiveProvider.createFromProvider(provider, annotation);
}
}
@ -200,29 +201,29 @@ export class EventEmitterAccessor {
}
}
function _createEventEmitterAccessors(bwv: BindingWithVisibility): EventEmitterAccessor[] {
var binding = bwv.binding;
if (!(binding instanceof DirectiveBinding)) return [];
var db = <DirectiveBinding>binding;
function _createEventEmitterAccessors(bwv: ProviderWithVisibility): EventEmitterAccessor[] {
var provider = bwv.provider;
if (!(provider instanceof DirectiveProvider)) return [];
var db = <DirectiveProvider>provider;
return db.eventEmitters.map(eventConfig => {
var parsedEvent = EventConfig.parse(eventConfig);
return new EventEmitterAccessor(parsedEvent.eventName, reflector.getter(parsedEvent.fieldName));
});
}
function _createProtoQueryRefs(bindings: BindingWithVisibility[]): ProtoQueryRef[] {
function _createProtoQueryRefs(providers: ProviderWithVisibility[]): ProtoQueryRef[] {
var res = [];
ListWrapper.forEachWithIndex(bindings, (b, i) => {
if (b.binding instanceof DirectiveBinding) {
var directiveBinding = <DirectiveBinding>b.binding;
ListWrapper.forEachWithIndex(providers, (b, i) => {
if (b.provider instanceof DirectiveProvider) {
var directiveProvider = <DirectiveProvider>b.provider;
// field queries
var queries: QueryMetadataWithSetter[] = directiveBinding.queries;
var queries: QueryMetadataWithSetter[] = directiveProvider.queries;
queries.forEach(q => res.push(new ProtoQueryRef(i, q.setter, q.metadata)));
// queries passed into the constructor.
// TODO: remove this after constructor queries are no longer supported
var deps: DirectiveDependency[] =
<DirectiveDependency[]>directiveBinding.resolvedFactory.dependencies;
<DirectiveDependency[]>directiveProvider.resolvedFactory.dependencies;
deps.forEach(d => {
if (isPresent(d.queryDecorator)) res.push(new ProtoQueryRef(i, null, d.queryDecorator));
});
@ -238,67 +239,67 @@ export class ProtoElementInjector {
protoQueryRefs: ProtoQueryRef[];
protoInjector: ProtoInjector;
static create(parent: ProtoElementInjector, index: number, bindings: DirectiveBinding[],
firstBindingIsComponent: boolean, distanceToParent: number,
static create(parent: ProtoElementInjector, index: number, providers: DirectiveProvider[],
firstProviderIsComponent: boolean, distanceToParent: number,
directiveVariableBindings: Map<string, number>): ProtoElementInjector {
var bd = [];
ProtoElementInjector._createDirectiveBindingWithVisibility(bindings, bd,
firstBindingIsComponent);
if (firstBindingIsComponent) {
ProtoElementInjector._createViewBindingsWithVisibility(bindings, bd);
ProtoElementInjector._createDirectiveProviderWithVisibility(providers, bd,
firstProviderIsComponent);
if (firstProviderIsComponent) {
ProtoElementInjector._createViewProvidersWithVisibility(providers, bd);
}
ProtoElementInjector._createBindingsWithVisibility(bindings, bd);
return new ProtoElementInjector(parent, index, bd, distanceToParent, firstBindingIsComponent,
ProtoElementInjector._createProvidersWithVisibility(providers, bd);
return new ProtoElementInjector(parent, index, bd, distanceToParent, firstProviderIsComponent,
directiveVariableBindings);
}
private static _createDirectiveBindingWithVisibility(dirBindings: DirectiveBinding[],
bd: BindingWithVisibility[],
firstBindingIsComponent: boolean) {
dirBindings.forEach(dirBinding => {
bd.push(ProtoElementInjector._createBindingWithVisibility(firstBindingIsComponent, dirBinding,
dirBindings, dirBinding));
private static _createDirectiveProviderWithVisibility(dirProviders: DirectiveProvider[],
bd: ProviderWithVisibility[],
firstProviderIsComponent: boolean) {
dirProviders.forEach(dirProvider => {
bd.push(ProtoElementInjector._createProviderWithVisibility(
firstProviderIsComponent, dirProvider, dirProviders, dirProvider));
});
}
private static _createBindingsWithVisibility(dirBindings: DirectiveBinding[],
bd: BindingWithVisibility[]) {
var bindingsFromAllDirectives = [];
dirBindings.forEach(dirBinding => {
bindingsFromAllDirectives =
ListWrapper.concat(bindingsFromAllDirectives, dirBinding.bindings);
private static _createProvidersWithVisibility(dirProviders: DirectiveProvider[],
bd: ProviderWithVisibility[]) {
var providersFromAllDirectives = [];
dirProviders.forEach(dirProvider => {
providersFromAllDirectives =
ListWrapper.concat(providersFromAllDirectives, dirProvider.providers);
});
var resolved = Injector.resolve(bindingsFromAllDirectives);
resolved.forEach(b => bd.push(new BindingWithVisibility(b, Visibility.Public)));
var resolved = Injector.resolve(providersFromAllDirectives);
resolved.forEach(b => bd.push(new ProviderWithVisibility(b, Visibility.Public)));
}
private static _createBindingWithVisibility(firstBindingIsComponent: boolean,
dirBinding: DirectiveBinding,
dirBindings: DirectiveBinding[],
binding: ResolvedBinding) {
var isComponent = firstBindingIsComponent && dirBindings[0] === dirBinding;
return new BindingWithVisibility(binding,
isComponent ? Visibility.PublicAndPrivate : Visibility.Public);
private static _createProviderWithVisibility(firstProviderIsComponent: boolean,
dirProvider: DirectiveProvider,
dirProviders: DirectiveProvider[],
provider: ResolvedProvider) {
var isComponent = firstProviderIsComponent && dirProviders[0] === dirProvider;
return new ProviderWithVisibility(
provider, isComponent ? Visibility.PublicAndPrivate : Visibility.Public);
}
private static _createViewBindingsWithVisibility(dirBindings: DirectiveBinding[],
bd: BindingWithVisibility[]) {
var resolvedViewBindings = Injector.resolve(dirBindings[0].viewBindings);
resolvedViewBindings.forEach(b => bd.push(new BindingWithVisibility(b, Visibility.Private)));
private static _createViewProvidersWithVisibility(dirProviders: DirectiveProvider[],
bd: ProviderWithVisibility[]) {
var resolvedViewProviders = Injector.resolve(dirProviders[0].viewProviders);
resolvedViewProviders.forEach(b => bd.push(new ProviderWithVisibility(b, Visibility.Private)));
}
/** @internal */
public _firstBindingIsComponent: boolean;
public _firstProviderIsComponent: boolean;
constructor(public parent: ProtoElementInjector, public index: number,
bwv: BindingWithVisibility[], public distanceToParent: number,
_firstBindingIsComponent: boolean,
bwv: ProviderWithVisibility[], public distanceToParent: number,
_firstProviderIsComponent: boolean,
public directiveVariableBindings: Map<string, number>) {
this._firstBindingIsComponent = _firstBindingIsComponent;
this._firstProviderIsComponent = _firstProviderIsComponent;
var length = bwv.length;
this.protoInjector = new ProtoInjector(bwv);
this.eventEmitterAccessors = ListWrapper.createFixedSize(length);
@ -316,7 +317,7 @@ export class ProtoElementInjector {
get hasBindings(): boolean { return this.eventEmitterAccessors.length > 0; }
getBindingAtIndex(index: number): any { return this.protoInjector.getBindingAtIndex(index); }
getProviderAtIndex(index: number): any { return this.protoInjector.getProviderAtIndex(index); }
}
class _Context {
@ -456,12 +457,12 @@ export class ElementInjector extends TreeNode<ElementInjector> implements Depend
isComponentKey(key: Key): boolean { return this._strategy.isComponentKey(key); }
getDependency(injector: Injector, binding: ResolvedBinding, dep: Dependency): any {
getDependency(injector: Injector, provider: ResolvedProvider, dep: Dependency): any {
var key: Key = dep.key;
if (binding instanceof DirectiveBinding) {
if (provider instanceof DirectiveProvider) {
var dirDep = <DirectiveDependency>dep;
var dirBin = binding;
var dirProvider = provider;
var staticKeys = StaticKeys.instance();
@ -475,7 +476,7 @@ export class ElementInjector extends TreeNode<ElementInjector> implements Depend
if (dirDep.key.id === StaticKeys.instance().changeDetectorRefId) {
// We provide the component's view change detector to components and
// the surrounding component's change detector to directives.
if (dirBin.metadata instanceof ComponentMetadata) {
if (dirProvider.metadata instanceof ComponentMetadata) {
var componentView = this._preBuiltObjects.view.getNestedView(
this._preBuiltObjects.elementRef.boundElementIndex);
return componentView.changeDetector.ref;
@ -498,12 +499,12 @@ export class ElementInjector extends TreeNode<ElementInjector> implements Depend
return null;
}
throw new NoBindingError(null, dirDep.key);
throw new NoProviderError(null, dirDep.key);
}
return this._preBuiltObjects.templateRef;
}
} else if (binding instanceof PipeBinding) {
} else if (provider instanceof PipeProvider) {
if (dep.key.id === StaticKeys.instance().changeDetectorRefId) {
var componentView = this._preBuiltObjects.view.getNestedView(
this._preBuiltObjects.elementRef.boundElementIndex);
@ -753,7 +754,7 @@ interface _ElementInjectorStrategy {
}
/**
* Strategy used by the `ElementInjector` when the number of bindings is 10 or less.
* Strategy used by the `ElementInjector` when the number of providers is 10 or less.
* In such a case, inlining fields is beneficial for performances.
*/
class ElementInjectorInlineStrategy implements _ElementInjectorStrategy {
@ -764,26 +765,26 @@ class ElementInjectorInlineStrategy implements _ElementInjectorStrategy {
var p = i.protoStrategy;
i.resetConstructionCounter();
if (p.binding0 instanceof DirectiveBinding && isPresent(p.keyId0) && i.obj0 === UNDEFINED)
i.obj0 = i.instantiateBinding(p.binding0, p.visibility0);
if (p.binding1 instanceof DirectiveBinding && isPresent(p.keyId1) && i.obj1 === UNDEFINED)
i.obj1 = i.instantiateBinding(p.binding1, p.visibility1);
if (p.binding2 instanceof DirectiveBinding && isPresent(p.keyId2) && i.obj2 === UNDEFINED)
i.obj2 = i.instantiateBinding(p.binding2, p.visibility2);
if (p.binding3 instanceof DirectiveBinding && isPresent(p.keyId3) && i.obj3 === UNDEFINED)
i.obj3 = i.instantiateBinding(p.binding3, p.visibility3);
if (p.binding4 instanceof DirectiveBinding && isPresent(p.keyId4) && i.obj4 === UNDEFINED)
i.obj4 = i.instantiateBinding(p.binding4, p.visibility4);
if (p.binding5 instanceof DirectiveBinding && isPresent(p.keyId5) && i.obj5 === UNDEFINED)
i.obj5 = i.instantiateBinding(p.binding5, p.visibility5);
if (p.binding6 instanceof DirectiveBinding && isPresent(p.keyId6) && i.obj6 === UNDEFINED)
i.obj6 = i.instantiateBinding(p.binding6, p.visibility6);
if (p.binding7 instanceof DirectiveBinding && isPresent(p.keyId7) && i.obj7 === UNDEFINED)
i.obj7 = i.instantiateBinding(p.binding7, p.visibility7);
if (p.binding8 instanceof DirectiveBinding && isPresent(p.keyId8) && i.obj8 === UNDEFINED)
i.obj8 = i.instantiateBinding(p.binding8, p.visibility8);
if (p.binding9 instanceof DirectiveBinding && isPresent(p.keyId9) && i.obj9 === UNDEFINED)
i.obj9 = i.instantiateBinding(p.binding9, p.visibility9);
if (p.provider0 instanceof DirectiveProvider && isPresent(p.keyId0) && i.obj0 === UNDEFINED)
i.obj0 = i.instantiateProvider(p.provider0, p.visibility0);
if (p.provider1 instanceof DirectiveProvider && isPresent(p.keyId1) && i.obj1 === UNDEFINED)
i.obj1 = i.instantiateProvider(p.provider1, p.visibility1);
if (p.provider2 instanceof DirectiveProvider && isPresent(p.keyId2) && i.obj2 === UNDEFINED)
i.obj2 = i.instantiateProvider(p.provider2, p.visibility2);
if (p.provider3 instanceof DirectiveProvider && isPresent(p.keyId3) && i.obj3 === UNDEFINED)
i.obj3 = i.instantiateProvider(p.provider3, p.visibility3);
if (p.provider4 instanceof DirectiveProvider && isPresent(p.keyId4) && i.obj4 === UNDEFINED)
i.obj4 = i.instantiateProvider(p.provider4, p.visibility4);
if (p.provider5 instanceof DirectiveProvider && isPresent(p.keyId5) && i.obj5 === UNDEFINED)
i.obj5 = i.instantiateProvider(p.provider5, p.visibility5);
if (p.provider6 instanceof DirectiveProvider && isPresent(p.keyId6) && i.obj6 === UNDEFINED)
i.obj6 = i.instantiateProvider(p.provider6, p.visibility6);
if (p.provider7 instanceof DirectiveProvider && isPresent(p.keyId7) && i.obj7 === UNDEFINED)
i.obj7 = i.instantiateProvider(p.provider7, p.visibility7);
if (p.provider8 instanceof DirectiveProvider && isPresent(p.keyId8) && i.obj8 === UNDEFINED)
i.obj8 = i.instantiateProvider(p.provider8, p.visibility8);
if (p.provider9 instanceof DirectiveProvider && isPresent(p.keyId9) && i.obj9 === UNDEFINED)
i.obj9 = i.instantiateProvider(p.provider9, p.visibility9);
}
dehydrate() {
@ -805,34 +806,44 @@ class ElementInjectorInlineStrategy implements _ElementInjectorStrategy {
var i = this.injectorStrategy;
var p = i.protoStrategy;
if (p.binding0 instanceof DirectiveBinding && (<DirectiveBinding>p.binding0).callOnDestroy) {
if (p.provider0 instanceof DirectiveProvider &&
(<DirectiveProvider>p.provider0).callOnDestroy) {
i.obj0.onDestroy();
}
if (p.binding1 instanceof DirectiveBinding && (<DirectiveBinding>p.binding1).callOnDestroy) {
if (p.provider1 instanceof DirectiveProvider &&
(<DirectiveProvider>p.provider1).callOnDestroy) {
i.obj1.onDestroy();
}
if (p.binding2 instanceof DirectiveBinding && (<DirectiveBinding>p.binding2).callOnDestroy) {
if (p.provider2 instanceof DirectiveProvider &&
(<DirectiveProvider>p.provider2).callOnDestroy) {
i.obj2.onDestroy();
}
if (p.binding3 instanceof DirectiveBinding && (<DirectiveBinding>p.binding3).callOnDestroy) {
if (p.provider3 instanceof DirectiveProvider &&
(<DirectiveProvider>p.provider3).callOnDestroy) {
i.obj3.onDestroy();
}
if (p.binding4 instanceof DirectiveBinding && (<DirectiveBinding>p.binding4).callOnDestroy) {
if (p.provider4 instanceof DirectiveProvider &&
(<DirectiveProvider>p.provider4).callOnDestroy) {
i.obj4.onDestroy();
}
if (p.binding5 instanceof DirectiveBinding && (<DirectiveBinding>p.binding5).callOnDestroy) {
if (p.provider5 instanceof DirectiveProvider &&
(<DirectiveProvider>p.provider5).callOnDestroy) {
i.obj5.onDestroy();
}
if (p.binding6 instanceof DirectiveBinding && (<DirectiveBinding>p.binding6).callOnDestroy) {
if (p.provider6 instanceof DirectiveProvider &&
(<DirectiveProvider>p.provider6).callOnDestroy) {
i.obj6.onDestroy();
}
if (p.binding7 instanceof DirectiveBinding && (<DirectiveBinding>p.binding7).callOnDestroy) {
if (p.provider7 instanceof DirectiveProvider &&
(<DirectiveProvider>p.provider7).callOnDestroy) {
i.obj7.onDestroy();
}
if (p.binding8 instanceof DirectiveBinding && (<DirectiveBinding>p.binding8).callOnDestroy) {
if (p.provider8 instanceof DirectiveProvider &&
(<DirectiveProvider>p.provider8).callOnDestroy) {
i.obj8.onDestroy();
}
if (p.binding9 instanceof DirectiveBinding && (<DirectiveBinding>p.binding9).callOnDestroy) {
if (p.provider9 instanceof DirectiveProvider &&
(<DirectiveProvider>p.provider9).callOnDestroy) {
i.obj9.onDestroy();
}
}
@ -840,7 +851,7 @@ class ElementInjectorInlineStrategy implements _ElementInjectorStrategy {
getComponent(): any { return this.injectorStrategy.obj0; }
isComponentKey(key: Key): boolean {
return this._ei._proto._firstBindingIsComponent && isPresent(key) &&
return this._ei._proto._firstProviderIsComponent && isPresent(key) &&
key.id === this.injectorStrategy.protoStrategy.keyId0;
}
@ -848,51 +859,51 @@ class ElementInjectorInlineStrategy implements _ElementInjectorStrategy {
var i = this.injectorStrategy;
var p = i.protoStrategy;
if (isPresent(p.binding0) && p.binding0.key.token === query.selector) {
if (i.obj0 === UNDEFINED) i.obj0 = i.instantiateBinding(p.binding0, p.visibility0);
if (isPresent(p.provider0) && p.provider0.key.token === query.selector) {
if (i.obj0 === UNDEFINED) i.obj0 = i.instantiateProvider(p.provider0, p.visibility0);
list.push(i.obj0);
}
if (isPresent(p.binding1) && p.binding1.key.token === query.selector) {
if (i.obj1 === UNDEFINED) i.obj1 = i.instantiateBinding(p.binding1, p.visibility1);
if (isPresent(p.provider1) && p.provider1.key.token === query.selector) {
if (i.obj1 === UNDEFINED) i.obj1 = i.instantiateProvider(p.provider1, p.visibility1);
list.push(i.obj1);
}
if (isPresent(p.binding2) && p.binding2.key.token === query.selector) {
if (i.obj2 === UNDEFINED) i.obj2 = i.instantiateBinding(p.binding2, p.visibility2);
if (isPresent(p.provider2) && p.provider2.key.token === query.selector) {
if (i.obj2 === UNDEFINED) i.obj2 = i.instantiateProvider(p.provider2, p.visibility2);
list.push(i.obj2);
}
if (isPresent(p.binding3) && p.binding3.key.token === query.selector) {
if (i.obj3 === UNDEFINED) i.obj3 = i.instantiateBinding(p.binding3, p.visibility3);
if (isPresent(p.provider3) && p.provider3.key.token === query.selector) {
if (i.obj3 === UNDEFINED) i.obj3 = i.instantiateProvider(p.provider3, p.visibility3);
list.push(i.obj3);
}
if (isPresent(p.binding4) && p.binding4.key.token === query.selector) {
if (i.obj4 === UNDEFINED) i.obj4 = i.instantiateBinding(p.binding4, p.visibility4);
if (isPresent(p.provider4) && p.provider4.key.token === query.selector) {
if (i.obj4 === UNDEFINED) i.obj4 = i.instantiateProvider(p.provider4, p.visibility4);
list.push(i.obj4);
}
if (isPresent(p.binding5) && p.binding5.key.token === query.selector) {
if (i.obj5 === UNDEFINED) i.obj5 = i.instantiateBinding(p.binding5, p.visibility5);
if (isPresent(p.provider5) && p.provider5.key.token === query.selector) {
if (i.obj5 === UNDEFINED) i.obj5 = i.instantiateProvider(p.provider5, p.visibility5);
list.push(i.obj5);
}
if (isPresent(p.binding6) && p.binding6.key.token === query.selector) {
if (i.obj6 === UNDEFINED) i.obj6 = i.instantiateBinding(p.binding6, p.visibility6);
if (isPresent(p.provider6) && p.provider6.key.token === query.selector) {
if (i.obj6 === UNDEFINED) i.obj6 = i.instantiateProvider(p.provider6, p.visibility6);
list.push(i.obj6);
}
if (isPresent(p.binding7) && p.binding7.key.token === query.selector) {
if (i.obj7 === UNDEFINED) i.obj7 = i.instantiateBinding(p.binding7, p.visibility7);
if (isPresent(p.provider7) && p.provider7.key.token === query.selector) {
if (i.obj7 === UNDEFINED) i.obj7 = i.instantiateProvider(p.provider7, p.visibility7);
list.push(i.obj7);
}
if (isPresent(p.binding8) && p.binding8.key.token === query.selector) {
if (i.obj8 === UNDEFINED) i.obj8 = i.instantiateBinding(p.binding8, p.visibility8);
if (isPresent(p.provider8) && p.provider8.key.token === query.selector) {
if (i.obj8 === UNDEFINED) i.obj8 = i.instantiateProvider(p.provider8, p.visibility8);
list.push(i.obj8);
}
if (isPresent(p.binding9) && p.binding9.key.token === query.selector) {
if (i.obj9 === UNDEFINED) i.obj9 = i.instantiateBinding(p.binding9, p.visibility9);
if (isPresent(p.provider9) && p.provider9.key.token === query.selector) {
if (i.obj9 === UNDEFINED) i.obj9 = i.instantiateProvider(p.provider9, p.visibility9);
list.push(i.obj9);
}
}
}
/**
* Strategy used by the `ElementInjector` when the number of bindings is 10 or less.
* Strategy used by the `ElementInjector` when the number of providers is 10 or less.
* In such a case, inlining fields is beneficial for performances.
*/
class ElementInjectorDynamicStrategy implements _ElementInjectorStrategy {
@ -904,9 +915,9 @@ class ElementInjectorDynamicStrategy implements _ElementInjectorStrategy {
inj.resetConstructionCounter();
for (var i = 0; i < p.keyIds.length; i++) {
if (p.bindings[i] instanceof DirectiveBinding && isPresent(p.keyIds[i]) &&
if (p.providers[i] instanceof DirectiveProvider && isPresent(p.keyIds[i]) &&
inj.objs[i] === UNDEFINED) {
inj.objs[i] = inj.instantiateBinding(p.bindings[i], p.visibilities[i]);
inj.objs[i] = inj.instantiateProvider(p.providers[i], p.visibilities[i]);
}
}
}
@ -920,9 +931,9 @@ class ElementInjectorDynamicStrategy implements _ElementInjectorStrategy {
var ist = this.injectorStrategy;
var p = ist.protoStrategy;
for (var i = 0; i < p.bindings.length; i++) {
if (p.bindings[i] instanceof DirectiveBinding &&
(<DirectiveBinding>p.bindings[i]).callOnDestroy) {
for (var i = 0; i < p.providers.length; i++) {
if (p.providers[i] instanceof DirectiveProvider &&
(<DirectiveProvider>p.providers[i]).callOnDestroy) {
ist.objs[i].onDestroy();
}
}
@ -932,17 +943,17 @@ class ElementInjectorDynamicStrategy implements _ElementInjectorStrategy {
isComponentKey(key: Key): boolean {
var p = this.injectorStrategy.protoStrategy;
return this._ei._proto._firstBindingIsComponent && isPresent(key) && key.id === p.keyIds[0];
return this._ei._proto._firstProviderIsComponent && isPresent(key) && key.id === p.keyIds[0];
}
addDirectivesMatchingQuery(query: QueryMetadata, list: any[]): void {
var ist = this.injectorStrategy;
var p = ist.protoStrategy;
for (var i = 0; i < p.bindings.length; i++) {
if (p.bindings[i].key.token === query.selector) {
for (var i = 0; i < p.providers.length; i++) {
if (p.providers[i].key.token === query.selector) {
if (ist.objs[i] === UNDEFINED) {
ist.objs[i] = ist.instantiateBinding(p.bindings[i], p.visibilities[i]);
ist.objs[i] = ist.instantiateProvider(p.providers[i], p.visibilities[i]);
}
list.push(ist.objs[i]);
}
@ -1025,7 +1036,7 @@ export class QueryRef {
private _visitInjector(inj: ElementInjector, aggregator: any[]) {
if (this.protoQueryRef.query.isVarBindingQuery) {
this._aggregateVariableBindings(inj, aggregator);
this._aggregateVariableBinding(inj, aggregator);
} else {
this._aggregateDirective(inj, aggregator);
}
@ -1049,7 +1060,7 @@ export class QueryRef {
}
}
private _aggregateVariableBindings(inj: ElementInjector, aggregator: any[]): void {
private _aggregateVariableBinding(inj: ElementInjector, aggregator: any[]): void {
var vb = this.protoQueryRef.query.varBindings;
for (var i = 0; i < vb.length; ++i) {
if (inj.hasVariableBinding(vb[i])) {

View File

@ -3,14 +3,14 @@ import {isPresent, isBlank, Type, isArray, isNumber} from 'angular2/src/core/fac
import {RenderProtoViewRef} from 'angular2/src/core/render/api';
import {Injectable, Binding, resolveForwardRef, Inject} from 'angular2/src/core/di';
import {Injectable, Provider, resolveForwardRef, Inject} from 'angular2/src/core/di';
import {PipeBinding} from '../pipes/pipe_binding';
import {PipeProvider} from '../pipes/pipe_provider';
import {ProtoPipes} from '../pipes/pipes';
import {AppProtoView, AppProtoViewMergeInfo, ViewType} from './view';
import {ElementBinder} from './element_binder';
import {ProtoElementInjector, DirectiveBinding} from './element_injector';
import {ProtoElementInjector, DirectiveProvider} from './element_injector';
import {DirectiveResolver} from './directive_resolver';
import {ViewResolver} from './view_resolver';
import {PipeResolver} from './pipe_resolver';
@ -55,7 +55,7 @@ export class ProtoViewFactory {
var result = this._cache.get(compiledTemplate.id);
if (isBlank(result)) {
var templateData = compiledTemplate.getData(this._appId);
var emptyMap: {[key: string]: PipeBinding} = {};
var emptyMap: {[key: string]: PipeProvider} = {};
result = new AppProtoView(templateData.commands, ViewType.HOST, true,
templateData.changeDetectorFactory, null, new ProtoPipes(emptyMap));
this._cache.set(compiledTemplate.id, result);
@ -76,7 +76,7 @@ export class ProtoViewFactory {
nestedProtoView = new AppProtoView(compiledTemplateData.commands, ViewType.COMPONENT, true,
compiledTemplateData.changeDetectorFactory, null,
ProtoPipes.fromBindings(boundPipes));
ProtoPipes.fromProviders(boundPipes));
// Note: The cache is updated before recursing
// to be able to resolve cycles
this._cache.set(cmd.template.id, nestedProtoView);
@ -112,9 +112,9 @@ export class ProtoViewFactory {
initializer.variableLocations);
}
private _bindPipe(typeOrBinding): PipeBinding {
let meta = this._pipeResolver.resolve(typeOrBinding);
return PipeBinding.createFromType(typeOrBinding, meta);
private _bindPipe(typeOrProvider): PipeProvider {
let meta = this._pipeResolver.resolve(typeOrProvider);
return PipeProvider.createFromType(typeOrProvider, meta);
}
private _flattenPipes(view: ViewMetadata): any[] {
@ -245,12 +245,12 @@ function _createElementBinder(directiveResolver: DirectiveResolver, nestedProtoV
if (isBlank(parentProtoElementInjector)) {
distanceToParentPei = -1;
}
var componentDirectiveBinding: DirectiveBinding = null;
var componentDirectiveProvider: DirectiveProvider = null;
var isEmbeddedTemplate = false;
var directiveBindings: DirectiveBinding[] =
beginElementCmd.directives.map(type => bindDirective(directiveResolver, type));
var directiveProviders: DirectiveProvider[] =
beginElementCmd.directives.map(type => provideDirective(directiveResolver, type));
if (beginElementCmd instanceof BeginComponentCmd) {
componentDirectiveBinding = directiveBindings[0];
componentDirectiveProvider = directiveProviders[0];
} else if (beginElementCmd instanceof EmbeddedTemplateCmd) {
isEmbeddedTemplate = true;
}
@ -262,29 +262,29 @@ function _createElementBinder(directiveResolver: DirectiveResolver, nestedProtoV
// so that, when hydrating, $implicit can be set to the element.
// - <template> elements need their own ElementInjector so that we can query their TemplateRef
var hasVariables = beginElementCmd.variableNameAndValues.length > 0;
if (directiveBindings.length > 0 || hasVariables || isEmbeddedTemplate) {
if (directiveProviders.length > 0 || hasVariables || isEmbeddedTemplate) {
var directiveVariableBindings = new Map<string, number>();
if (!isEmbeddedTemplate) {
directiveVariableBindings =
createDirectiveVariableBindings(beginElementCmd.variableNameAndValues, directiveBindings);
directiveVariableBindings = createDirectiveVariableBindings(
beginElementCmd.variableNameAndValues, directiveProviders);
}
protoElementInjector = ProtoElementInjector.create(
parentProtoElementInjector, boundElementIndex, directiveBindings,
isPresent(componentDirectiveBinding), distanceToParentPei, directiveVariableBindings);
parentProtoElementInjector, boundElementIndex, directiveProviders,
isPresent(componentDirectiveProvider), distanceToParentPei, directiveVariableBindings);
protoElementInjector.attributes = arrayToMap(beginElementCmd.attrNameAndValues, false);
}
return new ElementBinder(boundElementIndex, parentElementBinder, distanceToParentBinder,
protoElementInjector, componentDirectiveBinding, nestedProtoView);
protoElementInjector, componentDirectiveProvider, nestedProtoView);
}
function bindDirective(directiveResolver: DirectiveResolver, type: Type): DirectiveBinding {
function provideDirective(directiveResolver: DirectiveResolver, type: Type): DirectiveProvider {
let annotation = directiveResolver.resolve(type);
return DirectiveBinding.createFromType(type, annotation);
return DirectiveProvider.createFromType(type, annotation);
}
export function createDirectiveVariableBindings(variableNameAndValues: Array<string | number>,
directiveBindings: DirectiveBinding[]):
directiveProviders: DirectiveProvider[]):
Map<string, number> {
var directiveVariableBindings = new Map<string, number>();
for (var i = 0; i < variableNameAndValues.length; i += 2) {
@ -313,7 +313,7 @@ function arrayToMap(arr: string[], inverse: boolean): Map<string, string> {
return result;
}
function _flattenList(tree: any[], out: Array<Type | Binding | any[]>): void {
function _flattenList(tree: any[], out: Array<Type | Provider | any[]>): void {
for (var i = 0; i < tree.length; i++) {
var item = resolveForwardRef(tree[i]);
if (isArray(item)) {

View File

@ -21,7 +21,7 @@ import {
ProtoElementInjector,
ElementInjector,
PreBuiltObjects,
DirectiveBinding
DirectiveProvider
} from './element_injector';
import {ElementBinder} from './element_binder';
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';

View File

@ -1,6 +1,6 @@
import {ListWrapper} from 'angular2/src/core/facade/collection';
import {unimplemented} from 'angular2/src/core/facade/exceptions';
import {ResolvedBinding} from 'angular2/src/core/di';
import {ResolvedProvider} from 'angular2/src/core/di';
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
import * as avmModule from './view_manager';
@ -75,13 +75,13 @@ export abstract class ViewContainerRef {
*
* If `index` is not specified, the new View will be inserted as the last View in the container.
*
* You can optionally specify `dynamicallyCreatedBindings`, which configure the {@link Injector}
* You can optionally specify `dynamicallyCreatedProviders`, which configure the {@link Injector}
* that will be created for the Host View.
*
* Returns the {@link HostViewRef} of the Host View created for the newly instantiated Component.
*/
abstract createHostView(protoViewRef?: ProtoViewRef, index?: number,
dynamicallyCreatedBindings?: ResolvedBinding[]): HostViewRef;
dynamicallyCreatedProviders?: ResolvedProvider[]): HostViewRef;
/**
* Inserts a View identified by a {@link ViewRef} into the container at the specified `index`.
@ -136,10 +136,10 @@ export class ViewContainerRef_ extends ViewContainerRef {
}
createHostView(protoViewRef: ProtoViewRef = null, index: number = -1,
dynamicallyCreatedBindings: ResolvedBinding[] = null): HostViewRef {
dynamicallyCreatedProviders: ResolvedProvider[] = null): HostViewRef {
if (index == -1) index = this.length;
return this.viewManager.createHostViewInContainer(this.element, index, protoViewRef,
dynamicallyCreatedBindings);
dynamicallyCreatedProviders);
}
// TODO(i): refactor insert+remove into move

View File

@ -1,9 +1,9 @@
import {
Injector,
Inject,
Binding,
Provider,
Injectable,
ResolvedBinding,
ResolvedProvider,
forwardRef
} from 'angular2/src/core/di';
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
@ -159,7 +159,7 @@ export abstract class AppViewManager {
*/
abstract createHostViewInContainer(viewContainerLocation: ElementRef, index: number,
protoViewRef: ProtoViewRef,
imperativelyCreatedInjector: ResolvedBinding[]): HostViewRef;
imperativelyCreatedInjector: ResolvedProvider[]): HostViewRef;
/**
* Destroys an Embedded or Host View attached to a View Container at the specified `index`.
@ -278,7 +278,7 @@ export class AppViewManager_ extends AppViewManager {
createHostViewInContainer(viewContainerLocation: ElementRef, index: number,
protoViewRef: ProtoViewRef,
imperativelyCreatedInjector: ResolvedBinding[]): HostViewRef {
imperativelyCreatedInjector: ResolvedProvider[]): HostViewRef {
var s = this._createHostViewInContainerScope();
var protoView = internalProtoView(protoViewRef);
if (protoView.type !== viewModule.ViewType.HOST) {
@ -297,7 +297,7 @@ export class AppViewManager_ extends AppViewManager {
*/
_createViewInContainer(viewContainerLocation: ElementRef, index: number,
protoView: viewModule.AppProtoView, context: ElementRef,
imperativelyCreatedInjector: ResolvedBinding[]): ViewRef {
imperativelyCreatedInjector: ResolvedProvider[]): ViewRef {
var parentView = internalView((<ElementRef_>viewContainerLocation).parentView);
var boundElementIndex = (<ElementRef_>viewContainerLocation).boundElementIndex;
var contextView = internalView((<ElementRef_>context).parentView);

View File

@ -1,4 +1,4 @@
import {Injector, Binding, Injectable, ResolvedBinding} from 'angular2/src/core/di';
import {Injector, Provider, Injectable, ResolvedProvider} from 'angular2/src/core/di';
import {ListWrapper, MapWrapper, Map, StringMapWrapper} from 'angular2/src/core/facade/collection';
import * as eli from './element_injector';
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
@ -156,7 +156,7 @@ export class AppViewManagerUtils {
hydrateViewInContainer(parentView: viewModule.AppView, boundElementIndex: number,
contextView: viewModule.AppView, contextBoundElementIndex: number,
index: number, imperativelyCreatedBindings: ResolvedBinding[]) {
index: number, imperativelyCreatedProviders: ResolvedProvider[]) {
if (isBlank(contextView)) {
contextView = parentView;
contextBoundElementIndex = boundElementIndex;
@ -165,8 +165,8 @@ export class AppViewManagerUtils {
var view = viewContainer.views[index];
var elementInjector = contextView.elementInjectors[contextBoundElementIndex];
var injector = isPresent(imperativelyCreatedBindings) ?
Injector.fromResolvedBindings(imperativelyCreatedBindings) :
var injector = isPresent(imperativelyCreatedProviders) ?
Injector.fromResolvedProviders(imperativelyCreatedProviders) :
null;
this._hydrateView(view, injector, elementInjector.getHost(), contextView.context,
contextView.locals);

View File

@ -19,7 +19,8 @@ class Directive extends DirectiveMetadata {
@deprecated List<String> properties,
@deprecated List<String> events,
Map<String, String> host,
List bindings, String exportAs, String moduleId,
@deprecated List bindings,
List providers, String exportAs, String moduleId,
Map<String, dynamic> queries})
: super(
selector: selector,
@ -29,6 +30,7 @@ class Directive extends DirectiveMetadata {
events: events,
host: host,
bindings: bindings,
providers: providers,
exportAs: exportAs,
moduleId: moduleId,
queries: queries);
@ -43,9 +45,10 @@ class Component extends ComponentMetadata {
@deprecated List<String> properties,
@deprecated List<String> events,
Map<String, String> host,
List bindings, String exportAs, String moduleId,
@deprecated List bindings, List providers, String exportAs, String moduleId,
Map<String, dynamic> queries,
List viewBindings, ChangeDetectionStrategy changeDetection,
@deprecated List viewBindings,
List viewProviders, ChangeDetectionStrategy changeDetection,
String templateUrl, String template, dynamic directives,
dynamic pipes, ViewEncapsulation encapsulation, List<String> styles,
List<String> styleUrls
@ -58,9 +61,11 @@ class Component extends ComponentMetadata {
events: events,
host: host,
bindings: bindings,
providers: providers,
exportAs: exportAs,
moduleId: moduleId,
viewBindings: viewBindings,
viewProviders: viewProviders,
queries: queries,
changeDetection: changeDetection,
templateUrl: templateUrl,

View File

@ -153,6 +153,7 @@ export interface DirectiveFactory {
events?: string[],
host?: {[key: string]: string},
bindings?: any[],
providers?: any[],
exportAs?: string,
moduleId?: string,
queries?: {[key: string]: any}
@ -165,6 +166,7 @@ export interface DirectiveFactory {
events?: string[],
host?: {[key: string]: string},
bindings?: any[],
providers?: any[],
exportAs?: string,
moduleId?: string,
queries?: {[key: string]: any}
@ -222,11 +224,14 @@ export interface ComponentFactory {
properties?: string[],
events?: string[],
host?: {[key: string]: string},
/* @deprecated */
bindings?: any[],
providers?: any[],
exportAs?: string,
moduleId?: string,
queries?: {[key: string]: any},
viewBindings?: any[],
viewProviders?: any[],
changeDetection?: ChangeDetectionStrategy,
templateUrl?: string,
template?: string,
@ -243,11 +248,15 @@ export interface ComponentFactory {
properties?: string[],
events?: string[],
host?: {[key: string]: string},
/* @deprecated */
bindings?: any[],
providers?: any[],
exportAs?: string,
moduleId?: string,
queries?: {[key: string]: any},
/* @deprecated */
viewBindings?: any[],
viewProviders?: any[],
changeDetection?: ChangeDetectionStrategy,
templateUrl?: string,
template?: string,

View File

@ -466,13 +466,13 @@ export class DirectiveMetadata extends InjectableMetadata {
* ```
*
*/
inputs: string[];
/**
* @deprecated
* Same as `inputs`. This is to enable easier migration.
*/
properties: string[];
get inputs(): string[] {
return isPresent(this._properties) && this._properties.length > 0 ? this._properties :
this._inputs;
}
get properties(): string[] { return this.inputs; }
private _inputs: string[];
private _properties: string[];
/**
* Enumerates the set of event-bound output properties.
@ -519,13 +519,12 @@ export class DirectiveMetadata extends InjectableMetadata {
* ```
*
*/
outputs: string[];
/**
* @deprecated
* Same as `outputs`. This is to enable easier migration.
*/
events: string[];
get outputs(): string[] {
return isPresent(this._events) && this._events.length > 0 ? this._events : this._outputs;
}
get events(): string[] { return this.outputs; }
private _outputs: string[];
private _events: string[];
/**
* Specify the events, actions, properties and attributes related to the host element.
@ -665,7 +664,14 @@ export class DirectiveMetadata extends InjectableMetadata {
* }
* ```
*/
bindings: any[];
get providers(): any[] {
return isPresent(this._bindings) && this._bindings.length > 0 ? this._bindings :
this._providers;
}
/** @deprecated */
get bindings(): any[] { return this.providers; }
private _providers: any[];
private _bindings: any[];
/**
* Defines the name that can be used in the template to assign this directive to a variable.
@ -751,33 +757,32 @@ export class DirectiveMetadata extends InjectableMetadata {
*/
queries: {[key: string]: any};
constructor({selector, inputs, outputs, properties, events, host, bindings, exportAs, moduleId,
queries}: {
constructor({selector, inputs, outputs, properties, events, host, bindings, providers, exportAs,
moduleId, queries}: {
selector?: string,
inputs?: string[],
outputs?: string[],
properties?: string[],
events?: string[],
host?: {[key: string]: string},
bindings?: any[],
providers?: any[],
/** @deprecated */ bindings?: any[],
exportAs?: string,
moduleId?: string,
queries?: {[key: string]: any}
} = {}) {
super();
this.selector = selector;
this.inputs = inputs;
this.outputs = outputs;
this._inputs = inputs;
this._properties = properties;
this._outputs = outputs;
this._events = events;
this.host = host;
// TODO: remove this once properties and events are removed.
this.properties = properties;
this.events = events;
this.exportAs = exportAs;
this.moduleId = moduleId;
this.queries = queries;
this.bindings = bindings;
this._providers = providers;
this._bindings = bindings;
}
}
@ -792,7 +797,7 @@ export class DirectiveMetadata extends InjectableMetadata {
* When a component is instantiated, Angular
* - creates a shadow DOM for the component.
* - loads the selected template into the shadow DOM.
* - creates all the injectable objects configured with `bindings` and `viewBindings`.
* - creates all the injectable objects configured with `providers` and `viewProviders`.
*
* All template expressions and statements are then evaluated against the component instance.
*
@ -862,7 +867,7 @@ export class ComponentMetadata extends DirectiveMetadata {
*
* @Component({
* selector: 'greet',
* viewBindings: [
* viewProviders: [
* Greeter
* ]
* })
@ -875,7 +880,13 @@ export class ComponentMetadata extends DirectiveMetadata {
*
* ```
*/
viewBindings: any[];
get viewProviders(): any[] {
return isPresent(this._viewBindings) && this._viewBindings.length > 0 ? this._viewBindings :
this._viewProviders;
}
get viewBindings(): any[] { return this.viewProviders; }
private _viewProviders: any[];
private _viewBindings: any[];
templateUrl: string;
@ -892,18 +903,21 @@ export class ComponentMetadata extends DirectiveMetadata {
encapsulation: ViewEncapsulation;
constructor({selector, inputs, outputs, properties, events, host, exportAs, moduleId, bindings,
viewBindings, changeDetection = ChangeDetectionStrategy.Default, queries,
templateUrl, template, styleUrls, styles, directives, pipes, encapsulation}: {
providers, viewBindings, viewProviders,
changeDetection = ChangeDetectionStrategy.Default, queries, templateUrl, template,
styleUrls, styles, directives, pipes, encapsulation}: {
selector?: string,
inputs?: string[],
outputs?: string[],
properties?: string[],
events?: string[],
host?: {[key: string]: string},
bindings?: any[],
/** @deprecated */ bindings?: any[],
providers?: any[],
exportAs?: string,
moduleId?: string,
viewBindings?: any[],
/** @deprecated */ viewBindings?: any[],
viewProviders?: any[],
queries?: {[key: string]: any},
changeDetection?: ChangeDetectionStrategy,
templateUrl?: string,
@ -924,12 +938,13 @@ export class ComponentMetadata extends DirectiveMetadata {
exportAs: exportAs,
moduleId: moduleId,
bindings: bindings,
providers: providers,
queries: queries
});
this.changeDetection = changeDetection;
this.viewBindings = viewBindings;
this._viewProviders = viewProviders;
this._viewBindings = viewBindings;
this.templateUrl = templateUrl;
this.template = template;
this.styleUrls = styleUrls;

View File

@ -7,7 +7,7 @@ import {DatePipe} from './date_pipe';
import {DecimalPipe, PercentPipe, CurrencyPipe} from './number_pipe';
import {CONST_EXPR} from 'angular2/src/core/facade/lang';
import {Binding, OpaqueToken} from 'angular2/src/core/di';
import {Provider, OpaqueToken} from 'angular2/src/core/di';
const DEFAULT_PIPES_LIST = CONST_EXPR([
AsyncPipe,
@ -23,5 +23,5 @@ const DEFAULT_PIPES_LIST = CONST_EXPR([
export const DEFAULT_PIPES_TOKEN: OpaqueToken = CONST_EXPR(new OpaqueToken("Default Pipes"));
export const DEFAULT_PIPES: Binding =
CONST_EXPR(new Binding(DEFAULT_PIPES_TOKEN, {toValue: DEFAULT_PIPES_LIST}));
export const DEFAULT_PIPES: Provider =
CONST_EXPR(new Provider(DEFAULT_PIPES_TOKEN, {toValue: DEFAULT_PIPES_LIST}));

View File

@ -1,18 +0,0 @@
import {Type} from 'angular2/src/core/facade/lang';
import {ResolvedFactory, resolveBinding, ResolvedBinding_} from 'angular2/src/core/di/binding';
import {Key, ResolvedBinding, Binding} from 'angular2/src/core/di';
import {PipeMetadata} from '../metadata/directives';
export class PipeBinding extends ResolvedBinding_ {
constructor(public name: string, public pure: boolean, key: Key,
resolvedFactories: ResolvedFactory[], multiBinding: boolean) {
super(key, resolvedFactories, multiBinding);
}
static createFromType(type: Type, metadata: PipeMetadata): PipeBinding {
var binding = new Binding(type, {toClass: type});
var rb = resolveBinding(binding);
return new PipeBinding(metadata.name, metadata.pure, rb.key, rb.resolvedFactories,
rb.multiBinding);
}
}

View File

@ -0,0 +1,18 @@
import {Type} from 'angular2/src/core/facade/lang';
import {ResolvedFactory, resolveProvider, ResolvedProvider_} from 'angular2/src/core/di/provider';
import {Key, ResolvedProvider, Provider} from 'angular2/src/core/di';
import {PipeMetadata} from '../metadata/directives';
export class PipeProvider extends ResolvedProvider_ {
constructor(public name: string, public pure: boolean, key: Key,
resolvedFactories: ResolvedFactory[], multiBinding: boolean) {
super(key, resolvedFactories, multiBinding);
}
static createFromType(type: Type, metadata: PipeMetadata): PipeProvider {
var provider = new Provider(type, {toClass: type});
var rb = resolveProvider(provider);
return new PipeProvider(metadata.name, metadata.pure, rb.key, rb.resolvedFactories,
rb.multiProvider);
}
}

View File

@ -5,17 +5,17 @@ import {
Injectable,
OptionalMetadata,
SkipSelfMetadata,
Binding,
Provider,
Injector,
bind
} from 'angular2/src/core/di';
import {PipeBinding} from './pipe_binding';
import {PipeProvider} from './pipe_provider';
import * as cd from 'angular2/src/core/change_detection/pipes';
export class ProtoPipes {
static fromBindings(bindings: PipeBinding[]): ProtoPipes {
var config: {[key: string]: PipeBinding} = {};
bindings.forEach(b => config[b.name] = b);
static fromProviders(providers: PipeProvider[]): ProtoPipes {
var config: {[key: string]: PipeProvider} = {};
providers.forEach(b => config[b.name] = b);
return new ProtoPipes(config);
}
@ -23,14 +23,14 @@ export class ProtoPipes {
/**
* Map of {@link PipeMetadata} names to {@link PipeMetadata} implementations.
*/
public config: {[key: string]: PipeBinding}) {
public config: {[key: string]: PipeProvider}) {
this.config = config;
}
get(name: string): PipeBinding {
var binding = this.config[name];
if (isBlank(binding)) throw new BaseException(`Cannot find pipe '${name}'.`);
return binding;
get(name: string): PipeProvider {
var provider = this.config[name];
if (isBlank(provider)) throw new BaseException(`Cannot find pipe '${name}'.`);
return provider;
}
}

View File

@ -7,4 +7,6 @@ import 'package:angular2/src/core/dom/dom_adapter.dart';
exceptionFactory() => new ExceptionHandler(DOM, true);
const EXCEPTION_BINDING = const Binding(ExceptionHandler, toFactory: exceptionFactory, deps: const []);
const EXCEPTION_PROVIDER = const Binding(ExceptionHandler, toFactory: exceptionFactory, deps: const []);
const EXCEPTION_BINDING = EXCEPTION_PROVIDER;

View File

@ -1,6 +1,8 @@
import {bind} from 'angular2/src/core/di';
import {provide} from 'angular2/src/core/di';
import {ExceptionHandler} from 'angular2/src/core/facade/exceptions';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
export const EXCEPTION_BINDING =
bind(ExceptionHandler).toFactory(() => new ExceptionHandler(DOM, false), []);
export const EXCEPTION_PROVIDER =
provide(ExceptionHandler, {asFactory: () => new ExceptionHandler(DOM, false), deps: []});
export const EXCEPTION_BINDING = EXCEPTION_PROVIDER;

View File

@ -15,8 +15,12 @@ class PublicTestability {
whenStable(callback: Function) { this._testability.whenStable(callback); }
findBindings(using: any, binding: string, exactMatch: boolean): any[] {
return this._testability.findBindings(using, binding, exactMatch);
findBindings(using: any, provider: string, exactMatch: boolean): any[] {
return this.findProviders(using, provider, exactMatch);
}
findProviders(using: any, provider: string, exactMatch: boolean): any[] {
return this._testability.findBindings(using, provider, exactMatch);
}
}

View File

@ -72,7 +72,12 @@ export class Testability {
// check for stability.
isAngularEventPending(): boolean { return this._isAngularEventPending; }
findBindings(using: any, binding: string, exactMatch: boolean): any[] {
findBindings(using: any, provider: string, exactMatch: boolean): any[] {
// TODO(juliemr): implement.
return [];
}
findProviders(using: any, provider: string, exactMatch: boolean): any[] {
// TODO(juliemr): implement.
return [];
}

View File

@ -91,7 +91,7 @@ export class MockConnection implements Connection {
/**
* A mock backend for testing the {@link Http} service.
*
* This class can be injected in tests, and should be used to override bindings
* This class can be injected in tests, and should be used to override providers
* to other backends, such as {@link XHRBackend}.
*
* #Example
@ -102,9 +102,9 @@ export class MockConnection implements Connection {
* var connection;
* var injector = Injector.resolveAndCreate([
* MockBackend,
* bind(Http).toFactory((backend, defaultOptions) => {
* provide(Http, {asFactory: (backend, defaultOptions) => {
* return new Http(backend, defaultOptions)
* }, [MockBackend, DefaultOptions])]);
* }, deps: [MockBackend, DefaultOptions]})]);
* var http = injector.get(Http);
* var backend = injector.get(MockBackend);
* //Assign any newly-created connection to local variable
@ -137,9 +137,9 @@ export class MockBackend implements ConnectionBackend {
* var text; //this will be set from mock response
* var injector = Injector.resolveAndCreate([
* MockBackend,
* bind(Http).toFactory(backend, options) {
* provide(Http, {asFactory: (backend, options) {
* return new Http(backend, options);
* }, [MockBackend, BaseRequestOptions]]);
* }, deps: [MockBackend, BaseRequestOptions]}]);
* var backend = injector.get(MockBackend);
* var http = injector.get(Http);
* backend.connections.subscribe(c => connection = c);

View File

@ -91,13 +91,13 @@ export class XHRConnection implements Connection {
* #Example
*
* ```
* import {Http, MyNodeBackend, HTTP_BINDINGS, BaseRequestOptions} from 'angular2/http';
* import {Http, MyNodeBackend, HTTP_PROVIDERS, BaseRequestOptions} from 'angular2/http';
* @Component({
* viewBindings: [
* HTTP_BINDINGS,
* bind(Http).toFactory((backend, options) => {
* viewProviders: [
* HTTP_PROVIDERS,
* provide(Http, {asFactory: (backend, options) => {
* return new Http(backend, options);
* }, [MyNodeBackend, BaseRequestOptions])]
* }, deps: [MyNodeBackend, BaseRequestOptions]})]
* })
* class MyComponent {
* constructor(http:Http) {

View File

@ -117,15 +117,15 @@ export class RequestOptions {
* ### Example ([live demo](http://plnkr.co/edit/LEKVSx?p=preview))
*
* ```typescript
* import {bind, bootstrap} from 'angular2/angular2';
* import {HTTP_BINDINGS, Http, BaseRequestOptions, RequestOptions} from 'angular2/http';
* import {provide, bootstrap} from 'angular2/angular2';
* import {HTTP_PROVIDERS, Http, BaseRequestOptions, RequestOptions} from 'angular2/http';
* import {App} from './myapp';
*
* class MyOptions extends BaseRequestOptions {
* search: string = 'coreTeam=true';
* }
*
* bootstrap(App, [HTTP_BINDINGS, bind(RequestOptions).toClass(MyOptions)]);
* bootstrap(App, [HTTP_PROVIDERS, provide(RequestOptions, {asClass: MyOptions})]);
* ```
*
* The options could also be extended when manually creating a {@link Request}

View File

@ -115,15 +115,16 @@ export class ResponseOptions {
* ### Example ([live demo](http://plnkr.co/edit/qv8DLT?p=preview))
*
* ```typescript
* import {bind, bootstrap} from 'angular2/angular2';
* import {HTTP_BINDINGS, Headers, Http, BaseResponseOptions, ResponseOptions} from 'angular2/http';
* import {provide, bootstrap} from 'angular2/angular2';
* import {HTTP_PROVIDERS, Headers, Http, BaseResponseOptions, ResponseOptions} from
* 'angular2/http';
* import {App} from './myapp';
*
* class MyOptions extends BaseResponseOptions {
* headers:Headers = new Headers({network: 'github'});
* }
*
* bootstrap(App, [HTTP_BINDINGS, bind(ResponseOptions).toClass(MyOptions)]);
* bootstrap(App, [HTTP_PROVIDERS, provide(ResponseOptions, {asClass: MyOptions})]);
* ```
*
* The options could also be extended when manually creating a {@link Response}

View File

@ -39,8 +39,8 @@ function mergeOptions(defaultOpts, providedOpts, method, url): RequestOptions {
* #Example
*
* ```typescript
* import {Http, HTTP_BINDINGS} from 'angular2/http';
* @Component({selector: 'http-app', viewBindings: [HTTP_BINDINGS]})
* import {Http, HTTP_PROVIDERS} from 'angular2/http';
* @Component({selector: 'http-app', viewProviders: [HTTP_PROVIDERS]})
* @View({templateUrl: 'people.html'})
* class PeopleComponent {
* constructor(http: Http) {
@ -63,7 +63,7 @@ function mergeOptions(defaultOpts, providedOpts, method, url): RequestOptions {
*
* The default construct used to perform requests, `XMLHttpRequest`, is abstracted as a "Backend" (
* {@link XHRBackend} in this case), which could be mocked with dependency injection by replacing
* the {@link XHRBackend} binding, as in the following example:
* the {@link XHRBackend} provider, as in the following example:
*
* #Example
*
@ -72,11 +72,11 @@ function mergeOptions(defaultOpts, providedOpts, method, url): RequestOptions {
* var injector = Injector.resolveAndCreate([
* BaseRequestOptions,
* MockBackend,
* bind(Http).toFactory(
* provide(Http, {asFactory:
* function(backend, defaultOptions) {
* return new Http(backend, defaultOptions);
* },
* [MockBackend, BaseRequestOptions])
* deps: [MockBackend, BaseRequestOptions]})
* ]);
* var http = injector.get(Http);
* http.get('request-from-mock-backend.json').subscribe((res:Response) => doSomething(res));

View File

@ -1,7 +1,7 @@
// Index to be used if Http is ever configured as a standalone npm package.
// require('reflect-metadata');
// require('es6-shim');
// import {HTTP_BINDINGS, JSONP_BINDINGS, Http, Jsonp} from './http';
// import {HTTP_PROVIDERS, JSONP_PROVIDERS, Http, Jsonp} from './http';
// import {Injector} from 'angular2/angular2';
// export * from './http';
@ -9,5 +9,5 @@
// * TODO(jeffbcross): export each as their own top-level file, to require as:
// * require('angular2/http'); require('http/jsonp');
// */
// export var http = Injector.resolveAndCreate([HTTP_BINDINGS]).get(Http);
// export var jsonp = Injector.resolveAndCreate([JSONP_BINDINGS]).get(Jsonp);
// export var http = Injector.resolveAndCreate([HTTP_PROVIDERS]).get(Http);
// export var jsonp = Injector.resolveAndCreate([JSONP_PROVIDERS]).get(Jsonp);

View File

@ -26,7 +26,7 @@ import {
*
* ```typescript
* import {Injectable, Injector} from 'angular2/angular2';
* import {HTTP_BINDINGS, Http, Request, RequestMethods} from 'angular2/http';
* import {HTTP_PROVIDERS, Http, Request, RequestMethods} from 'angular2/http';
*
* @Injectable()
* class AutoAuthenticator {
@ -40,7 +40,7 @@ import {
* }
* }
*
* var injector = Injector.resolveAndCreate([HTTP_BINDINGS, AutoAuthenticator]);
* var injector = Injector.resolveAndCreate([HTTP_PROVIDERS, AutoAuthenticator]);
* var authenticator = injector.get(AutoAuthenticator);
* authenticator.request('people.json').subscribe(res => {
* //URL should have included '?password=123'

View File

@ -4,24 +4,24 @@ import {DirectiveMetadata, ComponentMetadata} from '../core/metadata';
import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver';
export class MockDirectiveResolver extends DirectiveResolver {
private _bindingsOverrides = new Map<Type, any[]>();
private _viewBindingsOverrides = new Map<Type, any[]>();
private _providerOverrides = new Map<Type, any[]>();
private viewProviderOverrides = new Map<Type, any[]>();
resolve(type: Type): DirectiveMetadata {
var dm = super.resolve(type);
var bindingsOverride = this._bindingsOverrides.get(type);
var viewBindingsOverride = this._viewBindingsOverrides.get(type);
var providerOverrides = this._providerOverrides.get(type);
var viewProviderOverrides = this.viewProviderOverrides.get(type);
var bindings = dm.bindings;
if (isPresent(bindingsOverride)) {
bindings = dm.bindings.concat(bindingsOverride);
var providers = dm.providers;
if (isPresent(providerOverrides)) {
providers = dm.providers.concat(providerOverrides);
}
if (dm instanceof ComponentMetadata) {
var viewBindings = dm.viewBindings;
if (isPresent(viewBindingsOverride)) {
viewBindings = dm.viewBindings.concat(viewBindingsOverride);
var viewProviders = dm.viewProviders;
if (isPresent(viewProviderOverrides)) {
viewProviders = dm.viewProviders.concat(viewProviderOverrides);
}
return new ComponentMetadata({
@ -29,12 +29,12 @@ export class MockDirectiveResolver extends DirectiveResolver {
inputs: dm.inputs,
outputs: dm.outputs,
host: dm.host,
bindings: bindings,
exportAs: dm.exportAs,
moduleId: dm.moduleId,
queries: dm.queries,
changeDetection: dm.changeDetection,
viewBindings: viewBindings
providers: providers,
viewProviders: viewProviders
});
}
@ -43,18 +43,32 @@ export class MockDirectiveResolver extends DirectiveResolver {
inputs: dm.inputs,
outputs: dm.outputs,
host: dm.host,
bindings: bindings,
providers: providers,
exportAs: dm.exportAs,
moduleId: dm.moduleId,
queries: dm.queries
});
}
/**
* @deprecated
*/
setBindingsOverride(type: Type, bindings: any[]): void {
this._bindingsOverrides.set(type, bindings);
this._providerOverrides.set(type, bindings);
}
/**
* @deprecated
*/
setViewBindingsOverride(type: Type, viewBindings: any[]): void {
this._viewBindingsOverrides.set(type, viewBindings);
this.viewProviderOverrides.set(type, viewBindings);
}
setProvidersOverride(type: Type, bindings: any[]): void {
this._providerOverrides.set(type, bindings);
}
setViewProvidersOverride(type: Type, viewBindings: any[]): void {
this.viewProviderOverrides.set(type, viewBindings);
}
}

View File

@ -18,7 +18,7 @@ import {EventListener, History, Location} from 'angular2/src/core/facade/browser
* import {Component, View} from 'angular2/angular2';
* import {
* ROUTER_DIRECTIVES,
* ROUTER_BINDINGS,
* ROUTER_PROVIDERS,
* RouteConfig,
* Location
* } from 'angular2/router';
@ -34,7 +34,7 @@ import {EventListener, History, Location} from 'angular2/src/core/facade/browser
* }
* }
*
* bootstrap(AppCmp, [ROUTER_BINDINGS]);
* bootstrap(AppCmp, [ROUTER_PROVIDERS]);
* ```
*/
@Injectable()

View File

@ -16,7 +16,7 @@ import {Url} from './url_parser';
*
* ```
* import {bootstrap, Component, View} from 'angular2/angular2';
* import {Router, ROUTER_DIRECTIVES, ROUTER_BINDINGS, RouteConfig} from 'angular2/router';
* import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig} from 'angular2/router';
*
* @Component({...})
* @View({directives: [ROUTER_DIRECTIVES]})
@ -34,7 +34,7 @@ import {Url} from './url_parser';
* }
* }
*
* bootstrap(AppCmp, ROUTER_BINDINGS);
* bootstrap(AppCmp, ROUTER_PROVIDERS);
* ```
*/
export class RouteParams {
@ -54,7 +54,7 @@ export class RouteParams {
*
* ```
* import {bootstrap, Component, View} from 'angular2/angular2';
* import {Router, ROUTER_DIRECTIVES, ROUTER_BINDINGS, RouteConfig} from 'angular2/router';
* import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig} from 'angular2/router';
*
* @Component({...})
* @View({directives: [ROUTER_DIRECTIVES]})
@ -68,7 +68,7 @@ export class RouteParams {
* }
* }
*
* bootstrap(AppCmp, ROUTER_BINDINGS);
* bootstrap(AppCmp, ROUTER_PROVIDERS);
* ```
*/
export class Instruction {

View File

@ -9,7 +9,7 @@ import {OpaqueToken, Injectable, Optional, Inject} from 'angular2/src/core/di';
* The `APP_BASE_HREF` token represents the base href to be used with the
* {@link PathLocationStrategy}.
*
* If you're using {@link PathLocationStrategy}, you must provide a binding to a string
* If you're using {@link PathLocationStrategy}, you must provide a provider to a string
* representing the URL prefix that should be preserved when generating and recognizing
* URLs.
*
@ -17,7 +17,7 @@ import {OpaqueToken, Injectable, Optional, Inject} from 'angular2/src/core/di';
*
* ```
* import {Component, View} from 'angular2/angular2';
* import {ROUTER_DIRECTIVES, ROUTER_BINDINGS, RouteConfig} from 'angular2/router';
* import {ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig} from 'angular2/router';
*
* @Component({...})
* @View({directives: [ROUTER_DIRECTIVES]})
@ -29,9 +29,9 @@ import {OpaqueToken, Injectable, Optional, Inject} from 'angular2/src/core/di';
* }
*
* bootstrap(AppCmp, [
* ROUTER_BINDINGS,
* ROUTER_PROVIDERS,
* PathLocationStrategy,
* bind(APP_BASE_HREF).toValue('/my/app')
* provide(APP_BASE_HREF, {asValue: '/my/app'})
* ]);
* ```
*/
@ -59,7 +59,7 @@ export const APP_BASE_HREF: OpaqueToken = CONST_EXPR(new OpaqueToken('appBaseHre
* import {Component, View} from 'angular2/angular2';
* import {
* ROUTER_DIRECTIVES,
* ROUTER_BINDINGS,
* ROUTER_PROVIDERS,
* RouteConfig,
* Location
* } from 'angular2/router';
@ -75,7 +75,7 @@ export const APP_BASE_HREF: OpaqueToken = CONST_EXPR(new OpaqueToken('appBaseHre
* }
* }
*
* bootstrap(AppCmp, [ROUTER_BINDINGS]);
* bootstrap(AppCmp, [ROUTER_PROVIDERS]);
* ```
*/
@Injectable()
@ -91,7 +91,7 @@ export class Location {
if (isBlank(browserBaseHref)) {
throw new BaseException(
`No base href set. Either provide a binding for the APP_BASE_HREF token or add a base element to the document.`);
`No base href set. Either provide a provider for the APP_BASE_HREF token or add a base element to the document.`);
}
this._baseHref = stripTrailingSlash(stripIndexHtml(browserBaseHref));

View File

@ -10,9 +10,9 @@ import {LocationStrategy} from './location_strategy';
* browser's URL.
*
* `PathLocationStrategy` is the default binding for {@link LocationStrategy}
* provided in {@link ROUTER_BINDINGS}.
* provided in {@link ROUTER_PROVIDERS}.
*
* If you're using `PathLocationStrategy`, you must provide a binding for
* If you're using `PathLocationStrategy`, you must provide a provider for
* {@link APP_BASE_HREF} to a string representing the URL prefix that should
* be preserved when generating and recognizing URLs.
*
@ -23,11 +23,11 @@ import {LocationStrategy} from './location_strategy';
* ## Example
*
* ```
* import {Component, View, bind} from 'angular2/angular2';
* import {Component, View, provide} from 'angular2/angular2';
* import {
* APP_BASE_HREF
* ROUTER_DIRECTIVES,
* ROUTER_BINDINGS,
* ROUTER_PROVIDERS,
* RouteConfig,
* Location
* } from 'angular2/router';
@ -44,8 +44,8 @@ import {LocationStrategy} from './location_strategy';
* }
*
* bootstrap(AppCmp, [
* ROUTER_BINDINGS, // includes binding to PathLocationStrategy
* bind(APP_BASE_HREF).toValue('/my/app')
* ROUTER_PROVIDERS, // includes binding to PathLocationStrategy
* provide(APP_BASE_HREF, {asValue: '/my/app'})
* ]);
* ```
*/

View File

@ -5,7 +5,7 @@ import {BaseException, WrappedException} from 'angular2/src/core/facade/exceptio
import {Directive, Attribute} from 'angular2/src/core/metadata';
import {DynamicComponentLoader, ComponentRef, ElementRef} from 'angular2/src/core/linker';
import {Injector, bind, Dependency} from 'angular2/src/core/di';
import {Injector, provide, Dependency} from 'angular2/src/core/di';
import * as routerMod from './router';
import {ComponentInstruction, RouteParams} from './instruction';
@ -50,13 +50,12 @@ export class RouterOutlet {
var componentType = nextInstruction.componentType;
var childRouter = this._parentRouter.childRouter(componentType);
var bindings = Injector.resolve([
bind(ROUTE_DATA)
.toValue(nextInstruction.routeData()),
bind(RouteParams).toValue(new RouteParams(nextInstruction.params)),
bind(routerMod.Router).toValue(childRouter)
var providers = Injector.resolve([
provide(ROUTE_DATA, {asValue: nextInstruction.routeData()}),
provide(RouteParams, {asValue: new RouteParams(nextInstruction.params)}),
provide(routerMod.Router, {asValue: childRouter})
]);
return this._loader.loadNextToLocation(componentType, this._elementRef, bindings)
return this._loader.loadNextToLocation(componentType, this._elementRef, providers)
.then((componentRef) => {
this._componentRef = componentRef;
if (hasLifecycleHook(hookMod.onActivate, componentType)) {

View File

@ -1,4 +1,4 @@
import {Injector, bind, Injectable} from 'angular2/src/core/di';
import {Injector, provide, Injectable} from 'angular2/src/core/di';
import {Type, isPresent, isBlank} from 'angular2/src/core/facade/lang';
import {Promise} from 'angular2/src/core/facade/async';
@ -130,45 +130,61 @@ export class TestComponentBuilder {
}
/**
* Overrides one or more injectables configured via `bindings` metadata property of a directive or
* Overrides one or more injectables configured via `providers` metadata property of a directive
* or
* component.
* Very useful when certain bindings need to be mocked out.
* Very useful when certain providers need to be mocked out.
*
* The bindings specified via this method are appended to the existing `bindings` causing the
* duplicated bindings to
* The providers specified via this method are appended to the existing `providers` causing the
* duplicated providers to
* be overridden.
*
* @param {Type} component
* @param {any[]} bindings
* @param {any[]} providers
*
* @return {TestComponentBuilder}
*/
overrideBindings(type: Type, bindings: any[]): TestComponentBuilder {
overrideProviders(type: Type, providers: any[]): TestComponentBuilder {
var clone = this._clone();
clone._bindingsOverrides.set(type, bindings);
clone._bindingsOverrides.set(type, providers);
return clone;
}
/**
* Overrides one or more injectables configured via `bindings` metadata property of a directive or
* @deprecated
*/
overrideBindings(type: Type, providers: any[]): TestComponentBuilder {
return this.overrideProviders(type, providers);
}
/**
* Overrides one or more injectables configured via `providers` metadata property of a directive
* or
* component.
* Very useful when certain bindings need to be mocked out.
* Very useful when certain providers need to be mocked out.
*
* The bindings specified via this method are appended to the existing `bindings` causing the
* duplicated bindings to
* The providers specified via this method are appended to the existing `providers` causing the
* duplicated providers to
* be overridden.
*
* @param {Type} component
* @param {any[]} bindings
* @param {any[]} providers
*
* @return {TestComponentBuilder}
*/
overrideViewBindings(type: Type, bindings: any[]): TestComponentBuilder {
overrideViewProviders(type: Type, providers: any[]): TestComponentBuilder {
var clone = this._clone();
clone._viewBindingsOverrides.set(type, bindings);
clone._viewBindingsOverrides.set(type, providers);
return clone;
}
/**
* @deprecated
*/
overrideViewBindings(type: Type, providers: any[]): TestComponentBuilder {
return this.overrideViewProviders(type, providers);
}
/**
* Builds and returns a RootTestComponent.
*

View File

@ -1,4 +1,4 @@
import {bind, Binding} from 'angular2/src/core/di';
import {provide, Provider} from 'angular2/src/core/di';
import {DEFAULT_PIPES} from 'angular2/src/core/pipes';
import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
import {MockAnimationBuilder} from 'angular2/src/mock/animation_builder_mock';
@ -38,7 +38,7 @@ import {MockNgZone} from 'angular2/src/mock/ng_zone_mock';
import {TestComponentBuilder} from './test_component_builder';
import {Injector} from 'angular2/src/core/di';
import {ELEMENT_PROBE_BINDINGS} from 'angular2/src/core/debug';
import {ELEMENT_PROBE_PROVIDERS} from 'angular2/src/core/debug';
import {ListWrapper} from 'angular2/src/core/facade/collection';
import {FunctionWrapper, Type} from 'angular2/src/core/facade/lang';
@ -56,27 +56,24 @@ import {
import {APP_ID} from 'angular2/src/core/application_tokens';
import {Serializer} from "angular2/src/web_workers/shared/serializer";
import {Log} from './utils';
import {compilerBindings} from 'angular2/src/core/compiler/compiler';
import {compilerProviders} from 'angular2/src/core/compiler/compiler';
import {DomRenderer_} from "angular2/src/core/render/dom/dom_renderer";
import {DynamicComponentLoader_} from "angular2/src/core/linker/dynamic_component_loader";
import {AppViewManager_} from "angular2/src/core/linker/view_manager";
/**
* Returns the root injector bindings.
* Returns the root injector providers.
*
* This must be kept in sync with the _rootBindings in application.js
*
* @returns {any[]}
*/
function _getRootBindings() {
return [
bind(Reflector)
.toValue(reflector),
];
function _getRootProviders() {
return [provide(Reflector, {asValue: reflector})];
}
/**
* Returns the application injector bindings.
* Returns the application injector providers.
*
* This must be kept in sync with _injectorBindings() in application.js
*
@ -93,43 +90,44 @@ function _getAppBindings() {
}
return [
compilerBindings(),
bind(ChangeDetectorGenConfig).toValue(new ChangeDetectorGenConfig(true, true, false, true)),
bind(DOCUMENT).toValue(appDoc),
bind(DomRenderer).toClass(DomRenderer_),
bind(Renderer).toAlias(DomRenderer),
bind(APP_ID).toValue('a'),
compilerProviders(),
provide(ChangeDetectorGenConfig,
{asValue: new ChangeDetectorGenConfig(true, true, false, true)}),
provide(DOCUMENT, {asValue: appDoc}),
provide(DomRenderer, {asClass: DomRenderer_}),
provide(Renderer, {asAlias: DomRenderer}),
provide(APP_ID, {asValue: 'a'}),
DomSharedStylesHost,
bind(SharedStylesHost).toAlias(DomSharedStylesHost),
provide(SharedStylesHost, {asAlias: DomSharedStylesHost}),
AppViewPool,
bind(AppViewManager).toClass(AppViewManager_),
provide(AppViewManager, {asClass: AppViewManager_}),
AppViewManagerUtils,
Serializer,
ELEMENT_PROBE_BINDINGS,
bind(APP_VIEW_POOL_CAPACITY).toValue(500),
ELEMENT_PROBE_PROVIDERS,
provide(APP_VIEW_POOL_CAPACITY, {asValue: 500}),
ProtoViewFactory,
bind(DirectiveResolver).toClass(MockDirectiveResolver),
bind(ViewResolver).toClass(MockViewResolver),
provide(DirectiveResolver, {asClass: MockDirectiveResolver}),
provide(ViewResolver, {asClass: MockViewResolver}),
DEFAULT_PIPES,
bind(IterableDiffers).toValue(defaultIterableDiffers),
bind(KeyValueDiffers).toValue(defaultKeyValueDiffers),
provide(IterableDiffers, {asValue: defaultIterableDiffers}),
provide(KeyValueDiffers, {asValue: defaultKeyValueDiffers}),
Log,
bind(DynamicComponentLoader).toClass(DynamicComponentLoader_),
provide(DynamicComponentLoader, {asClass: DynamicComponentLoader_}),
PipeResolver,
bind(ExceptionHandler).toValue(new ExceptionHandler(DOM)),
bind(LocationStrategy).toClass(MockLocationStrategy),
bind(XHR).toClass(MockXHR),
provide(ExceptionHandler, {asValue: new ExceptionHandler(DOM)}),
provide(LocationStrategy, {asClass: MockLocationStrategy}),
provide(XHR, {asClass: MockXHR}),
TestComponentBuilder,
bind(NgZone).toClass(MockNgZone),
bind(AnimationBuilder).toClass(MockAnimationBuilder),
provide(NgZone, {asClass: MockNgZone}),
provide(AnimationBuilder, {asClass: MockAnimationBuilder}),
EventManager,
new Binding(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true})
new Provider(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true})
];
}
export function createTestInjector(bindings: Array<Type | Binding | any[]>): Injector {
var rootInjector = Injector.resolveAndCreate(_getRootBindings());
return rootInjector.resolveAndCreateChild(ListWrapper.concat(_getAppBindings(), bindings));
export function createTestInjector(providers: Array<Type | Provider | any[]>): Injector {
var rootInjector = Injector.resolveAndCreate(_getRootProviders());
return rootInjector.resolveAndCreateChild(ListWrapper.concat(_getAppBindings(), providers));
}
/**

View File

@ -20,7 +20,7 @@ import 'package:angular2/src/core/dom/dom_adapter.dart' show DOM;
import 'package:angular2/src/core/reflection/reflection.dart';
import 'package:angular2/src/core/reflection/reflection_capabilities.dart';
import 'package:angular2/src/core/di/binding.dart' show bind;
import 'package:angular2/src/core/di/provider.dart' show bind;
import 'package:angular2/src/core/di/injector.dart' show Injector;
import 'package:angular2/src/core/facade/collection.dart' show StringMapWrapper;
@ -162,13 +162,18 @@ void beforeEach(fn) {
* bind(SomeToken).toValue(myValue),
* ]);
*/
void beforeEachBindings(Function fn) {
void beforeEachProviders(Function fn) {
gns.beforeEach(() {
var bindings = fn();
if (bindings != null) _testBindings.addAll(bindings);
}, priority: 2);
}
@Deprecated('using beforeEachProviders instead')
void beforeEachBindings(Function fn) {
beforeEachProviders(fn);
}
void _it(gnsFn, name, fn) {
if (fn is! FunctionWithParamTokens) fn = new FunctionWithParamTokens([], fn);
gnsFn(name, () {

View File

@ -3,7 +3,7 @@ import {StringMapWrapper} from 'angular2/src/core/facade/collection';
import {global, isFunction, Math} from 'angular2/src/core/facade/lang';
import {NgZoneZone} from 'angular2/src/core/zone/ng_zone';
import {bind} from 'angular2/src/core/di';
import {provide} from 'angular2/src/core/di';
import {createTestInjector, FunctionWithParamTokens, inject} from './test_injector';
import {browserDetection} from './utils';
@ -53,12 +53,12 @@ var runnerStack = [];
var inIt = false;
var globalTimeOut = browserDetection.isSlow ? 3000 : jasmine.DEFAULT_TIMEOUT_INTERVAL;
var testBindings;
var testProviders;
/**
* Mechanism to run `beforeEach()` functions of Angular tests.
*
* Note: Jasmine own `beforeEach` is used by this library to handle DI bindings.
* Note: Jasmine own `beforeEach` is used by this library to handle DI providers.
*/
class BeforeEachRunner {
private _fns: Array<FunctionWithParamTokens | SyncTestFn> = [];
@ -75,8 +75,8 @@ class BeforeEachRunner {
}
}
// Reset the test bindings before each test
jsmBeforeEach(() => { testBindings = []; });
// Reset the test providers before each test
jsmBeforeEach(() => { testProviders = []; });
function _describe(jsmFn, ...args) {
var parentRunner = runnerStack.length === 0 ? null : runnerStack[runnerStack.length - 1];
@ -110,25 +110,32 @@ export function beforeEach(fn: FunctionWithParamTokens | SyncTestFn): void {
}
/**
* Allows overriding default bindings defined in test_injector.js.
* Allows overriding default providers defined in test_injector.js.
*
* The given function must return a list of DI bindings.
* The given function must return a list of DI providers.
*
* Example:
*
* beforeEachBindings(() => [
* bind(Compiler).toClass(MockCompiler),
* bind(SomeToken).toValue(myValue),
* provide(Compiler, {asClass: MockCompiler}),
* provide(SomeToken, {asValue: myValue}),
* ]);
*/
export function beforeEachBindings(fn): void {
export function beforeEachProviders(fn): void {
jsmBeforeEach(() => {
var bindings = fn();
if (!bindings) return;
testBindings = [...testBindings, ...bindings];
testProviders = [...testProviders, ...bindings];
});
}
/**
* @deprecated
*/
export function beforeEachBindings(fn): void {
beforeEachProviders(fn);
}
function _it(jsmFn: Function, name: string, testFn: FunctionWithParamTokens | AnyTestFn,
testTimeOut: number): void {
var runner = runnerStack[runnerStack.length - 1];
@ -140,16 +147,15 @@ function _it(jsmFn: Function, name: string, testFn: FunctionWithParamTokens | An
if (testFn.hasToken(AsyncTestCompleter)) {
jsmFn(name, (done) => {
var completerBinding =
bind(AsyncTestCompleter)
.toFactory(() => {
// Mark the test as async when an AsyncTestCompleter is injected in an it()
if (!inIt)
throw new Error('AsyncTestCompleter can only be injected in an "it()"');
return new AsyncTestCompleter(done);
});
var completerProvider = provide(AsyncTestCompleter, {
asFactory: () => {
// Mark the test as async when an AsyncTestCompleter is injected in an it()
if (!inIt) throw new Error('AsyncTestCompleter can only be injected in an "it()"');
return new AsyncTestCompleter(done);
}
});
var injector = createTestInjector([...testBindings, completerBinding]);
var injector = createTestInjector([...testProviders, completerProvider]);
runner.run(injector);
inIt = true;
@ -158,7 +164,7 @@ function _it(jsmFn: Function, name: string, testFn: FunctionWithParamTokens | An
}, timeOut);
} else {
jsmFn(name, () => {
var injector = createTestInjector(testBindings);
var injector = createTestInjector(testProviders);
runner.run(injector);
testFn.execute(injector);
}, timeOut);
@ -169,13 +175,13 @@ function _it(jsmFn: Function, name: string, testFn: FunctionWithParamTokens | An
if ((<any>testFn).length === 0) {
jsmFn(name, () => {
var injector = createTestInjector(testBindings);
var injector = createTestInjector(testProviders);
runner.run(injector);
(<SyncTestFn>testFn)();
}, timeOut);
} else {
jsmFn(name, (done) => {
var injector = createTestInjector(testBindings);
var injector = createTestInjector(testProviders);
runner.run(injector);
(<AsyncTestFn>testFn)(done);
}, timeOut);

View File

@ -1,6 +1,6 @@
// TODO (jteplitz602): This whole file is nearly identical to core/application.ts.
// There should be a way to refactor application so that this file is unnecessary. See #3277
import {Injector, bind, Binding} from "angular2/src/core/di";
import {Injector, provide, Provider} from "angular2/src/core/di";
import {DEFAULT_PIPES} from 'angular2/src/core/pipes';
import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
import {BrowserDetails} from 'angular2/src/animate/browser_details';
@ -19,7 +19,7 @@ import {AppViewPool, APP_VIEW_POOL_CAPACITY} from 'angular2/src/core/linker/view
import {Renderer} from 'angular2/src/core/render/api';
import {AppRootUrl} from 'angular2/src/core/compiler/app_root_url';
import {DomRenderer, DomRenderer_, DOCUMENT} from 'angular2/src/core/render/render';
import {APP_ID_RANDOM_BINDING} from 'angular2/src/core/application_tokens';
import {APP_ID_RANDOM_PROVIDER} from 'angular2/src/core/application_tokens';
import {ElementSchemaRegistry} from 'angular2/src/core/compiler/schema/element_schema_registry';
import {
DomElementSchemaRegistry
@ -68,31 +68,30 @@ import {
var _rootInjector: Injector;
// Contains everything that is safe to share between applications.
var _rootBindings = [bind(Reflector).toValue(reflector)];
var _rootProviders = [provide(Reflector, {asValue: reflector})];
// TODO: This code is nearly identical to core/application. There should be a way to only write it
// once
function _injectorBindings(): any[] {
function _injectorProviders(): any[] {
return [
bind(DOCUMENT)
.toValue(DOM.defaultDoc()),
provide(DOCUMENT, {asValue: DOM.defaultDoc()}),
EventManager,
new Binding(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true}),
new Binding(EVENT_MANAGER_PLUGINS, {toClass: KeyEventsPlugin, multi: true}),
new Binding(EVENT_MANAGER_PLUGINS, {toClass: HammerGesturesPlugin, multi: true}),
bind(DomRenderer).toClass(DomRenderer_),
bind(Renderer).toAlias(DomRenderer),
APP_ID_RANDOM_BINDING,
new Provider(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true}),
new Provider(EVENT_MANAGER_PLUGINS, {toClass: KeyEventsPlugin, multi: true}),
new Provider(EVENT_MANAGER_PLUGINS, {toClass: HammerGesturesPlugin, multi: true}),
provide(DomRenderer, {asClass: DomRenderer_}),
provide(Renderer, {asAlias: DomRenderer}),
APP_ID_RANDOM_PROVIDER,
DomSharedStylesHost,
bind(SharedStylesHost).toAlias(DomSharedStylesHost),
provide(SharedStylesHost, {asAlias: DomSharedStylesHost}),
Serializer,
bind(ON_WEB_WORKER).toValue(false),
bind(ElementSchemaRegistry).toValue(new DomElementSchemaRegistry()),
provide(ON_WEB_WORKER, {asValue: false}),
provide(ElementSchemaRegistry, {asValue: new DomElementSchemaRegistry()}),
RenderViewWithFragmentsStore,
RenderProtoViewRefStore,
AppViewPool,
bind(APP_VIEW_POOL_CAPACITY).toValue(10000),
bind(AppViewManager).toClass(AppViewManager_),
provide(APP_VIEW_POOL_CAPACITY, {asValue: 10000}),
provide(AppViewManager, {asClass: AppViewManager_}),
AppViewManagerUtils,
AppViewListener,
ProtoViewFactory,
@ -101,28 +100,28 @@ function _injectorBindings(): any[] {
DirectiveResolver,
Parser,
Lexer,
bind(ExceptionHandler).toFactory(() => new ExceptionHandler(DOM), []),
bind(XHR).toValue(new XHRImpl()),
provide(ExceptionHandler, {asFactory: () => new ExceptionHandler(DOM), deps: []}),
provide(XHR, {asValue: new XHRImpl()}),
UrlResolver,
bind(DynamicComponentLoader).toClass(DynamicComponentLoader_),
provide(DynamicComponentLoader, {asClass: DynamicComponentLoader_}),
Testability,
AnchorBasedAppRootUrl,
bind(AppRootUrl).toAlias(AnchorBasedAppRootUrl),
provide(AppRootUrl, {asAlias: AnchorBasedAppRootUrl}),
WebWorkerApplication,
WebWorkerSetup,
MessageBasedXHRImpl,
MessageBasedRenderer,
bind(ServiceMessageBrokerFactory).toClass(ServiceMessageBrokerFactory_),
bind(ClientMessageBrokerFactory).toClass(ClientMessageBrokerFactory_),
provide(ServiceMessageBrokerFactory, {asClass: ServiceMessageBrokerFactory_}),
provide(ClientMessageBrokerFactory, {asClass: ClientMessageBrokerFactory_}),
BrowserDetails,
AnimationBuilder,
AnimationBuilder
];
}
export function createInjector(zone: NgZone, bus: MessageBus): Injector {
BrowserDomAdapter.makeCurrent();
_rootBindings.push(bind(NgZone).toValue(zone));
_rootBindings.push(bind(MessageBus).toValue(bus));
var injector: Injector = Injector.resolveAndCreate(_rootBindings);
return injector.resolveAndCreateChild(_injectorBindings());
_rootProviders.push(provide(NgZone, {asValue: zone}));
_rootProviders.push(provide(MessageBus, {asValue: bus}));
var injector: Injector = Injector.resolveAndCreate(_rootProviders);
return injector.resolveAndCreateChild(_injectorProviders());
}

View File

@ -24,7 +24,7 @@ import {
} from 'angular2/src/web_workers/shared/service_message_broker';
/**
* Creates a zone, sets up the DI bindings
* Creates a zone, sets up the DI providers
* And then creates a new WebWorkerMain object to handle messages from the worker
*/
export function bootstrapUICommon(bus: MessageBus): WebWorkerApplication {

View File

@ -4,7 +4,7 @@ import {
PostMessageBusSource
} from 'angular2/src/web_workers/shared/post_message_bus';
import {Type} from "angular2/src/core/facade/lang";
import {Binding, Injectable} from "angular2/src/core/di";
import {Provider, Injectable} from "angular2/src/core/di";
import {Map} from 'angular2/src/core/facade/collection';
import {Promise} from 'angular2/src/core/facade/async';
import {bootstrapWebWorkerCommon} from "angular2/src/web_workers/worker/application_common";
@ -28,7 +28,7 @@ var _postMessage: PostMessageInterface = <any>postMessage;
* See the bootstrap() docs for more details.
*/
export function bootstrapWebWorker(
appComponentType: Type, componentInjectableBindings: Array<Type | Binding | any[]> = null):
appComponentType: Type, componentInjectableProviders: Array<Type | Provider | any[]> = null):
Promise<ComponentRef> {
Parse5DomAdapter.makeCurrent();
var sink = new PostMessageBusSink({
@ -40,5 +40,5 @@ export function bootstrapWebWorker(
var source = new PostMessageBusSource();
var bus = new PostMessageBus(sink, source);
return bootstrapWebWorkerCommon(appComponentType, bus, componentInjectableBindings);
return bootstrapWebWorkerCommon(appComponentType, bus, componentInjectableProviders);
}

View File

@ -1,5 +1,5 @@
import {Injector, bind, OpaqueToken, Binding} from 'angular2/src/core/di';
import {FORM_BINDINGS} from 'angular2/src/core/forms';
import {Injector, provide, OpaqueToken, Provider} from 'angular2/src/core/di';
import {FORM_PROVIDERS} from 'angular2/src/core/forms';
import {
NumberWrapper,
Type,
@ -42,7 +42,7 @@ import {SETUP_CHANNEL} from 'angular2/src/web_workers/shared/messaging_api';
import {WebWorkerEventDispatcher} from 'angular2/src/web_workers/worker/event_dispatcher';
import {ComponentRef} from 'angular2/src/core/linker/dynamic_component_loader';
import {NgZone} from 'angular2/src/core/zone/ng_zone';
import {compilerBindings} from 'angular2/src/core/compiler/compiler';
import {compilerProviders} from 'angular2/src/core/compiler/compiler';
/**
* Initialize the Angular 'platform' on the page in a manner suitable for applications
@ -51,25 +51,25 @@ import {compilerBindings} from 'angular2/src/core/compiler/compiler';
*
* See {@link PlatformRef} for details on the Angular platform.
*
* # Without specified bindings
* # Without specified providers
*
* If no bindings are specified, `platform`'s behavior depends on whether an existing
* If no providers are specified, `platform`'s behavior depends on whether an existing
* platform exists:
*
* If no platform exists, a new one will be created with the default {@link platformBindings}.
*
* If a platform already exists, it will be returned (regardless of what bindings it
* If a platform already exists, it will be returned (regardless of what providers it
* was created with). This is a convenience feature, allowing for multiple applications
* to be loaded into the same platform without awareness of each other.
*
* # With specified bindings
* # With specified providers
*
* It is also possible to specify bindings to be made in the new platform. These bindings
* It is also possible to specify providers to be made in the new platform. These providers
* will be shared between all applications on the page. For example, an abstraction for
* the browser cookie jar should be bound at the platform level, because there is only one
* cookie jar regardless of how many applications on the age will be accessing it.
*
* If bindings are specified directly, `platform` will create the Angular platform with
* If providers are specified directly, `platform` will create the Angular platform with
* them if a platform did not exist already. If it did exist, however, an error will be
* thrown.
*
@ -80,7 +80,7 @@ import {compilerBindings} from 'angular2/src/core/compiler/compiler';
* web worker context. Applications that need direct access to the DOM should
* use `platform` from `core/application_common` instead.
*/
export function platform(bindings?: Array<Type | Binding | any[]>): PlatformRef {
export function platform(bindings?: Array<Type | Provider | any[]>): PlatformRef {
return platformCommon(bindings);
}
@ -91,30 +91,30 @@ class PrintLogger {
logGroupEnd() {}
}
function webWorkerBindings(appComponentType, bus: MessageBus, initData: {[key: string]: any}):
Array<Type | Binding | any[]> {
function webWorkerProviders(appComponentType, bus: MessageBus, initData: {[key: string]: any}):
Array<Type | Provider | any[]> {
return [
compilerBindings(),
compilerProviders(),
Serializer,
bind(MessageBus).toValue(bus),
bind(ClientMessageBrokerFactory).toClass(ClientMessageBrokerFactory_),
bind(ServiceMessageBrokerFactory).toClass(ServiceMessageBrokerFactory_),
provide(MessageBus, {asValue: bus}),
provide(ClientMessageBrokerFactory, {asClass: ClientMessageBrokerFactory_}),
provide(ServiceMessageBrokerFactory, {asClass: ServiceMessageBrokerFactory_}),
WebWorkerRenderer,
bind(Renderer).toAlias(WebWorkerRenderer),
bind(ON_WEB_WORKER).toValue(true),
provide(Renderer, {asAlias: WebWorkerRenderer}),
provide(ON_WEB_WORKER, {asValue: true}),
RenderViewWithFragmentsStore,
RenderProtoViewRefStore,
bind(ExceptionHandler).toFactory(() => new ExceptionHandler(new PrintLogger()), []),
provide(ExceptionHandler, {asFactory: () => new ExceptionHandler(new PrintLogger()), deps: []}),
WebWorkerXHRImpl,
bind(XHR).toAlias(WebWorkerXHRImpl),
bind(AppRootUrl).toValue(new AppRootUrl(initData['rootUrl'])),
provide(XHR, {asAlias: WebWorkerXHRImpl}),
provide(AppRootUrl, {asValue: new AppRootUrl(initData['rootUrl'])}),
WebWorkerEventDispatcher,
FORM_BINDINGS
FORM_PROVIDERS
];
}
export function bootstrapWebWorkerCommon(appComponentType: Type, bus: MessageBus,
appBindings: Array<Type | Binding | any[]> = null):
appProviders: Array<Type | Provider | any[]> = null):
Promise<ComponentRef> {
var bootstrapProcess: PromiseCompleter<any> = PromiseWrapper.completer();
var appPromise = platform().asyncApplication((zone: NgZone) => {
@ -128,9 +128,9 @@ export function bootstrapWebWorkerCommon(appComponentType: Type, bus: MessageBus
var emitter = bus.from(SETUP_CHANNEL);
subscription = ObservableWrapper.subscribe(emitter, (message: {[key: string]: any}) => {
var bindings =
[applicationCommonBindings(), webWorkerBindings(appComponentType, bus, message)];
if (isPresent(appBindings)) {
bindings.push(appBindings);
[applicationCommonBindings(), webWorkerProviders(appComponentType, bus, message)];
if (isPresent(appProviders)) {
bindings.push(appProviders);
}
bootstrapProcess.resolve(bindings);
ObservableWrapper.dispose(subscription);

View File

@ -17,7 +17,7 @@ import {Component, Directive, View} from 'angular2/core';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {DOCUMENT} from 'angular2/render';
import {PromiseWrapper} from 'angular2/src/core/facade/async';
import {bind, Inject, Injector, LifeCycle} from 'angular2/core';
import {provide, Inject, Injector, LifeCycle} from 'angular2/core';
import {ExceptionHandler} from 'angular2/src/core/facade/exceptions';
import {Testability, TestabilityRegistry} from 'angular2/src/core/testability/testability';
import {IS_DART} from '../platform';
@ -77,7 +77,7 @@ class _ArrayLogger {
export function main() {
var fakeDoc, el, el2, testBindings, lightDom;
var fakeDoc, el, el2, testProviders, lightDom;
describe('bootstrap factory method', () => {
beforeEach(() => {
@ -89,7 +89,7 @@ export function main() {
DOM.appendChild(fakeDoc.body, el2);
DOM.appendChild(el, lightDom);
DOM.setText(lightDom, 'loading');
testBindings = [bind(DOCUMENT).toValue(fakeDoc)];
testProviders = [provide(DOCUMENT, {asValue: fakeDoc})];
});
it('should throw if bootstrapped Directive is not a Component',
@ -98,7 +98,7 @@ export function main() {
var exceptionHandler = new ExceptionHandler(logger, false);
var refPromise =
bootstrap(HelloRootDirectiveIsNotCmp,
[testBindings, bind(ExceptionHandler).toValue(exceptionHandler)]);
[testProviders, provide(ExceptionHandler, {asValue: exceptionHandler})]);
PromiseWrapper.then(refPromise, null, (exception) => {
expect(exception).toContainError(
@ -114,7 +114,7 @@ export function main() {
var exceptionHandler = new ExceptionHandler(logger, IS_DART ? false : true);
var refPromise =
bootstrap(HelloRootCmp, [bind(ExceptionHandler).toValue(exceptionHandler)]);
bootstrap(HelloRootCmp, [provide(ExceptionHandler, {asValue: exceptionHandler})]);
PromiseWrapper.then(refPromise, null, (reason) => {
expect(reason.message).toContain('The selector "hello-app" did not match any elements');
async.done();
@ -129,7 +129,7 @@ export function main() {
var exceptionHandler = new ExceptionHandler(logger, IS_DART ? false : true);
var refPromise =
bootstrap(HelloRootCmp, [bind(ExceptionHandler).toValue(exceptionHandler)]);
bootstrap(HelloRootCmp, [provide(ExceptionHandler, {asValue: exceptionHandler})]);
PromiseWrapper.then(refPromise, null, (reason) => {
expect(logger.res.join(""))
.toContain('The selector "hello-app" did not match any elements');
@ -140,12 +140,12 @@ export function main() {
}
it('should create an injector promise', () => {
var refPromise = bootstrap(HelloRootCmp, testBindings);
var refPromise = bootstrap(HelloRootCmp, testProviders);
expect(refPromise).not.toBe(null);
});
it('should display hello world', inject([AsyncTestCompleter], (async) => {
var refPromise = bootstrap(HelloRootCmp, testBindings);
var refPromise = bootstrap(HelloRootCmp, testProviders);
refPromise.then((ref) => {
expect(el).toHaveText('hello world!');
async.done();
@ -153,8 +153,8 @@ export function main() {
}));
it('should support multiple calls to bootstrap', inject([AsyncTestCompleter], (async) => {
var refPromise1 = bootstrap(HelloRootCmp, testBindings);
var refPromise2 = bootstrap(HelloRootCmp2, testBindings);
var refPromise1 = bootstrap(HelloRootCmp, testProviders);
var refPromise2 = bootstrap(HelloRootCmp2, testProviders);
PromiseWrapper.all([refPromise1, refPromise2])
.then((refs) => {
expect(el).toHaveText('hello world!');
@ -165,8 +165,8 @@ export function main() {
it("should make the provided bindings available to the application component",
inject([AsyncTestCompleter], (async) => {
var refPromise =
bootstrap(HelloRootCmp3, [testBindings, bind("appBinding").toValue("BoundValue")]);
var refPromise = bootstrap(
HelloRootCmp3, [testProviders, provide("appBinding", {asValue: "BoundValue"})]);
refPromise.then((ref) => {
expect(ref.hostComponent.appBinding).toEqual("BoundValue");
@ -176,7 +176,7 @@ export function main() {
it("should avoid cyclic dependencies when root component requires Lifecycle through DI",
inject([AsyncTestCompleter], (async) => {
var refPromise = bootstrap(HelloRootCmp4, testBindings);
var refPromise = bootstrap(HelloRootCmp4, testProviders);
refPromise.then((ref) => {
expect(ref.hostComponent.lc).toBe((<ComponentRef_>ref).injector.get(LifeCycle));
@ -186,8 +186,8 @@ export function main() {
it('should register each application with the testability registry',
inject([AsyncTestCompleter], (async) => {
var refPromise1 = bootstrap(HelloRootCmp, testBindings);
var refPromise2 = bootstrap(HelloRootCmp2, testBindings);
var refPromise1 = bootstrap(HelloRootCmp, testProviders);
var refPromise2 = bootstrap(HelloRootCmp2, testProviders);
PromiseWrapper.all([refPromise1, refPromise2])
.then((refs: ApplicationRef[]) => {

View File

@ -1,7 +1,7 @@
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/test_lib';
import {SpyIterableDifferFactory} from '../../spies';
import {IterableDiffers} from 'angular2/src/core/change_detection/differs/iterable_differs';
import {Injector, bind} from 'angular2/core';
import {Injector, provide} from 'angular2/core';
export function main() {
describe('IterableDiffers', function() {
@ -50,7 +50,7 @@ export function main() {
it('should extend di-inherited diffesr', () => {
var parent = new IterableDiffers([factory1]);
var injector = Injector.resolveAndCreate([bind(IterableDiffers).toValue(parent)]);
var injector = Injector.resolveAndCreate([provide(IterableDiffers, {asValue: parent})]);
var childInjector = injector.resolveAndCreateChild([IterableDiffers.extend([factory2])]);
expect(injector.get(IterableDiffers).factories).toEqual([factory1]);

View File

@ -37,11 +37,11 @@ import {
} from 'angular2/src/core/compiler/change_definition_factory';
import {TestDirective, TestDispatcher, TestPipes} from './change_detector_mocks';
import {TEST_BINDINGS} from './test_bindings';
import {TEST_PROVIDERS} from './test_bindings';
export function main() {
describe('ChangeDefinitionFactory', () => {
beforeEachBindings(() => TEST_BINDINGS);
beforeEachBindings(() => TEST_PROVIDERS);
var parser: TemplateParser;
var dispatcher: TestDispatcher;

View File

@ -12,7 +12,7 @@ import {
inject,
beforeEachBindings
} from 'angular2/test_lib';
import {bind} from 'angular2/src/core/di';
import {provide} from 'angular2/src/core/di';
import {CONST_EXPR, stringify} from 'angular2/src/core/facade/lang';
import {MapWrapper} from 'angular2/src/core/facade/collection';
@ -45,7 +45,7 @@ import {
import {evalModule} from './eval_module';
import {TEST_BINDINGS} from './test_bindings';
import {TEST_PROVIDERS} from './test_bindings';
import {TestDispatcher, TestPipes} from './change_detector_mocks';
import {
codeGenValueFn,
@ -60,7 +60,7 @@ var THIS_MODULE_REF = moduleRef(THIS_MODULE_URL);
export function main() {
describe('ChangeDetectorCompiler', () => {
beforeEachBindings(() => TEST_BINDINGS);
beforeEachBindings(() => TEST_PROVIDERS);
var parser: TemplateParser;
var compiler: ChangeDetectionCompiler;
@ -83,8 +83,8 @@ export function main() {
describe('no jit', () => {
beforeEachBindings(() => [
bind(ChangeDetectorGenConfig)
.toValue(new ChangeDetectorGenConfig(true, true, false, false))
provide(ChangeDetectorGenConfig,
{asValue: new ChangeDetectorGenConfig(true, true, false, false)})
]);
it('should watch element properties', () => {
expect(detectChanges(compiler, '<div [el-prop]="someProp">'))
@ -94,8 +94,8 @@ export function main() {
describe('jit', () => {
beforeEachBindings(() => [
bind(ChangeDetectorGenConfig)
.toValue(new ChangeDetectorGenConfig(true, true, false, true))
provide(ChangeDetectorGenConfig,
{asValue: new ChangeDetectorGenConfig(true, true, false, true)})
]);
it('should watch element properties', () => {
expect(detectChanges(compiler, '<div [el-prop]="someProp">'))

View File

@ -43,7 +43,7 @@ import {
codeGenExportVariable,
MODULE_SUFFIX
} from 'angular2/src/core/compiler/util';
import {TEST_BINDINGS} from './test_bindings';
import {TEST_PROVIDERS} from './test_bindings';
const BEGIN_ELEMENT = 'BEGIN_ELEMENT';
const END_ELEMENT = 'END_ELEMENT';
@ -78,7 +78,7 @@ var NESTED_COMPONENT = new CompiledTemplate(45, () => []);
export function main() {
describe('CommandCompiler', () => {
beforeEachBindings(() => TEST_BINDINGS);
beforeEachBindings(() => TEST_PROVIDERS);
var parser: TemplateParser;
var commandCompiler: CommandCompiler;

View File

@ -13,7 +13,7 @@ import {
beforeEachBindings
} from 'angular2/test_lib';
import {Component, View, bind} from 'angular2/core';
import {Component, View, provide} from 'angular2/core';
import {PromiseWrapper} from 'angular2/src/core/facade/async';
import {SpyProtoViewFactory} from '../spies';
import {
@ -39,7 +39,7 @@ export function main() {
protoViewFactorySpy = new SpyProtoViewFactory();
someProtoView = new AppProtoView(null, null, null, null, null, null);
protoViewFactorySpy.spy('createHost').andReturn(someProtoView);
return [bind(ProtoViewFactory).toValue(protoViewFactorySpy)];
return [provide(ProtoViewFactory, {asValue: protoViewFactorySpy})];
});
it('should compile the template via TemplateCompiler',

View File

@ -33,12 +33,12 @@ import {
SimpleChange
} from 'angular2/core';
import {TEST_BINDINGS} from './test_bindings';
import {TEST_PROVIDERS} from './test_bindings';
import {MODULE_SUFFIX, IS_DART} from 'angular2/src/core/compiler/util';
export function main() {
describe('RuntimeMetadataResolver', () => {
beforeEachBindings(() => TEST_BINDINGS);
beforeEachBindings(() => TEST_PROVIDERS);
describe('getMetadata', () => {
it('should read metadata',

View File

@ -12,7 +12,7 @@ import {
inject,
beforeEachBindings
} from 'angular2/test_lib';
import {bind} from 'angular2/src/core/di';
import {provide} from 'angular2/src/core/di';
import {SpyXHR} from '../spies';
import {XHR} from 'angular2/src/core/compiler/xhr';
import {BaseException, WrappedException} from 'angular2/src/core/facade/exceptions';
@ -28,7 +28,7 @@ import {
} from 'angular2/src/core/compiler/directive_metadata';
import {SourceExpression, SourceModule} from 'angular2/src/core/compiler/source_module';
import {ViewEncapsulation} from 'angular2/src/core/metadata/view';
import {TEST_BINDINGS} from './test_bindings';
import {TEST_PROVIDERS} from './test_bindings';
import {
codeGenValueFn,
codeGenExportVariable,
@ -51,7 +51,7 @@ export function main() {
beforeEachBindings(() => {
xhr = <any>new SpyXHR();
return [TEST_BINDINGS, bind(XHR).toValue(xhr)];
return [TEST_PROVIDERS, provide(XHR, {asValue: xhr})];
});
var compiler: StyleCompiler;

View File

@ -42,9 +42,9 @@ import {
CompiledTemplate
} from 'angular2/src/core/linker/template_commands';
import {Component, View, Directive, bind} from 'angular2/core';
import {Component, View, Directive, provide} from 'angular2/core';
import {TEST_BINDINGS} from './test_bindings';
import {TEST_PROVIDERS} from './test_bindings';
import {TestDispatcher, TestPipes} from './change_detector_mocks';
import {
codeGenValueFn,
@ -64,7 +64,7 @@ export function main() {
var compiler: TemplateCompiler;
var runtimeMetadataResolver: RuntimeMetadataResolver;
beforeEachBindings(() => [bind(APP_ID).toValue(APP_ID_VALUE), TEST_BINDINGS]);
beforeEachBindings(() => [provide(APP_ID, {asValue: APP_ID_VALUE}), TEST_PROVIDERS]);
beforeEach(inject([TemplateCompiler, RuntimeMetadataResolver],
(_compiler, _runtimeMetadataResolver) => {
compiler = _compiler;

View File

@ -22,13 +22,13 @@ import {ViewEncapsulation} from 'angular2/src/core/metadata/view';
import {TemplateNormalizer} from 'angular2/src/core/compiler/template_normalizer';
import {XHR} from 'angular2/src/core/compiler/xhr';
import {MockXHR} from 'angular2/src/core/compiler/xhr_mock';
import {TEST_BINDINGS} from './test_bindings';
import {TEST_PROVIDERS} from './test_bindings';
export function main() {
describe('TemplateNormalizer', () => {
var dirType: CompileTypeMetadata;
beforeEachBindings(() => TEST_BINDINGS);
beforeEachBindings(() => TEST_PROVIDERS);
beforeEach(() => {
dirType = new CompileTypeMetadata({moduleUrl: 'package:some/module/a.js', name: 'SomeComp'});

View File

@ -10,9 +10,9 @@ import {
inject,
beforeEachBindings
} from 'angular2/test_lib';
import {bind} from 'angular2/src/core/di';
import {provide} from 'angular2/src/core/di';
import {TEST_BINDINGS} from './test_bindings';
import {TEST_PROVIDERS} from './test_bindings';
import {isPresent} from 'angular2/src/core/facade/lang';
import {TemplateParser, splitClasses} from 'angular2/src/core/compiler/template_parser';
import {
@ -48,9 +48,12 @@ var expressionUnparser = new Unparser();
export function main() {
describe('TemplateParser', () => {
beforeEachBindings(() => [
TEST_BINDINGS,
bind(ElementSchemaRegistry)
.toValue(new MockSchemaRegistry({'invalidProp': false}, {'mappedAttr': 'mappedProp'}))
TEST_PROVIDERS,
provide(ElementSchemaRegistry,
{
asValue: new MockSchemaRegistry({'invalidProp': false},
{'mappedAttr': 'mappedProp'})
})
]);
var parser: TemplateParser;

View File

@ -1,5 +1,6 @@
import {bind, Binding} from 'angular2/src/core/di';
import {provide, Provider} from 'angular2/src/core/di';
import {MockSchemaRegistry} from './schema_registry_mock';
import {ElementSchemaRegistry} from 'angular2/src/core/compiler/schema/element_schema_registry';
export var TEST_BINDINGS = [bind(ElementSchemaRegistry).toValue(new MockSchemaRegistry({}, {}))];
export var TEST_PROVIDERS =
[provide(ElementSchemaRegistry, {asValue: new MockSchemaRegistry({}, {})})];

View File

@ -61,7 +61,7 @@ class ChildComp {
constructor() { this.childBinding = 'Original'; }
}
@Component({selector: 'parent-comp', viewBindings: [Logger]})
@Component({selector: 'parent-comp', viewProviders: [Logger]})
@View({
template: `<div class="parent" message="parent">
<span class="parentnested" message="nestedparent">Parent</span>
@ -105,7 +105,7 @@ class EventsComp {
handleCustom() { this.customed = true; }
}
@Component({selector: 'using-for', viewBindings: [Logger]})
@Component({selector: 'using-for', viewProviders: [Logger]})
@View({
template: `<span *ng-for="#thing of stuff" [inner-html]="thing"></span>
<ul message="list">

View File

@ -15,7 +15,7 @@ import {
} from 'angular2/test_lib';
import {global} from 'angular2/src/core/facade/lang';
import {APP_VIEW_POOL_CAPACITY} from 'angular2/src/core/linker/view_pool';
import {bind, Component, Directive, Injectable, View} from 'angular2/core';
import {provide, Component, Directive, Injectable, View} from 'angular2/core';
import {inspectNativeElement} from 'angular2/src/core/debug';
import {IS_DART} from '../../platform';
@ -28,7 +28,7 @@ class MyComp {
export function main() {
describe('element probe', function() {
beforeEachBindings(() => [bind(APP_VIEW_POOL_CAPACITY).toValue(0)]);
beforeEachBindings(() => [provide(APP_VIEW_POOL_CAPACITY, {asValue: 0})]);
it('should return a TestElement from a dom element',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {

View File

@ -10,21 +10,21 @@ import {
xit,
} from 'angular2/test_lib';
import {bind} from 'angular2/core';
import {bind, provide} from 'angular2/core';
export function main() {
describe('binding', () => {
describe('provider', () => {
describe('type errors', () => {
it('should throw when trying to create a class binding and not passing a class', () => {
it('should throw when trying to create a class provider and not passing a class', () => {
expect(() => { bind('foo').toClass(<any>0); })
.toThrowError('Trying to create a class binding but "0" is not a class!');
.toThrowError('Trying to create a class provider but "0" is not a class!');
});
it('should throw when trying to create a factory binding and not passing a function', () => {
it('should throw when trying to create a factory provider and not passing a function', () => {
expect(() => { bind('foo').toFactory(<any>0); })
.toThrowError('Trying to create a factory binding but "0" is not a function!');
.toThrowError('Trying to create a factory provider but "0" is not a function!');
});
});
});

View File

@ -4,8 +4,8 @@ import {describe, ddescribe, it, iit, expect, beforeEach} from 'angular2/test_li
import {SpyDependencyProvider} from '../spies';
import {
Injector,
bind,
ResolvedBinding,
provide,
ResolvedProvider,
Key,
forwardRef,
Injectable,
@ -15,16 +15,16 @@ import {
SkipSelfMetadata,
Optional,
Inject,
Binding
Provider
} from 'angular2/core';
import {DependencyMetadata} from 'angular2/src/core/di/metadata';
import {ResolvedBinding_} from 'angular2/src/core/di/binding';
import {ResolvedProvider_} from 'angular2/src/core/di/provider';
import {
InjectorInlineStrategy,
InjectorDynamicStrategy,
ProtoInjector,
BindingWithVisibility,
ProviderWithVisibility,
Visibility
} from 'angular2/src/core/di/injector';
@ -89,29 +89,28 @@ class NoAnnotations {
}
export function main() {
var dynamicBindings = [
bind('binding0')
.toValue(1),
bind('binding1').toValue(1),
bind('binding2').toValue(1),
bind('binding3').toValue(1),
bind('binding4').toValue(1),
bind('binding5').toValue(1),
bind('binding6').toValue(1),
bind('binding7').toValue(1),
bind('binding8').toValue(1),
bind('binding9').toValue(1),
bind('binding10').toValue(1)
var dynamicProviders = [
provide('provider0', {asValue: 1}),
provide('provider1', {asValue: 1}),
provide('provider2', {asValue: 1}),
provide('provider3', {asValue: 1}),
provide('provider4', {asValue: 1}),
provide('provider5', {asValue: 1}),
provide('provider6', {asValue: 1}),
provide('provider7', {asValue: 1}),
provide('provider8', {asValue: 1}),
provide('provider9', {asValue: 1}),
provide('provider10', {asValue: 1})
];
[{strategy: 'inline', bindings: [], strategyClass: InjectorInlineStrategy},
[{strategy: 'inline', providers: [], strategyClass: InjectorInlineStrategy},
{
strategy: 'dynamic',
bindings: dynamicBindings,
providers: dynamicProviders,
strategyClass: InjectorDynamicStrategy
}].forEach((context) => {
function createInjector(bindings: any[]) {
return Injector.resolveAndCreate(bindings.concat(context['bindings']));
function createInjector(providers: any[]) {
return Injector.resolveAndCreate(providers.concat(context['providers']));
}
describe(`injector ${context['strategy']}`, () => {
@ -158,32 +157,33 @@ export function main() {
expect(e1).toBe(e2);
});
it('should bind to a value', () => {
var injector = createInjector([bind(Engine).toValue("fake engine")]);
it('should provide to a value', () => {
var injector = createInjector([provide(Engine, {asValue: "fake engine"})]);
var engine = injector.get(Engine);
expect(engine).toEqual("fake engine");
});
it('should bind to a factory', () => {
it('should provide to a factory', () => {
function sportsCarFactory(e) { return new SportsCar(e); }
var injector = createInjector([Engine, bind(Car).toFactory(sportsCarFactory, [Engine])]);
var injector =
createInjector([Engine, provide(Car, {asFactory: sportsCarFactory, deps: [Engine]})]);
var car = injector.get(Car);
expect(car).toBeAnInstanceOf(SportsCar);
expect(car.engine).toBeAnInstanceOf(Engine);
});
it('should supporting binding to null', () => {
var injector = createInjector([bind(Engine).toValue(null)]);
it('should supporting provider to null', () => {
var injector = createInjector([provide(Engine, {asValue: null})]);
var engine = injector.get(Engine);
expect(engine).toBeNull();
});
it('should bind to an alias', () => {
it('should provide to an alias', () => {
var injector = createInjector(
[Engine, bind(SportsCar).toClass(SportsCar), bind(Car).toAlias(SportsCar)]);
[Engine, provide(SportsCar, {asClass: SportsCar}), provide(Car, {asAlias: SportsCar})]);
var car = injector.get(Car);
var sportsCar = injector.get(SportsCar);
@ -191,11 +191,11 @@ export function main() {
expect(car).toBe(sportsCar);
});
it('should support multibindings', () => {
it('should support multiProviders', () => {
var injector = createInjector([
Engine,
new Binding(Car, {toClass: SportsCar, multi: true}),
new Binding(Car, {toClass: CarWithOptionalEngine, multi: true})
new Provider(Car, {toClass: SportsCar, multi: true}),
new Provider(Car, {toClass: CarWithOptionalEngine, multi: true})
]);
var cars = injector.get(Car);
@ -204,37 +204,32 @@ export function main() {
expect(cars[1]).toBeAnInstanceOf(CarWithOptionalEngine);
});
it('should support multibindings that are created using toAlias', () => {
it('should support multiProviders that are created using toAlias', () => {
var injector = createInjector(
[Engine, SportsCar, new Binding(Car, {toAlias: SportsCar, multi: true})]);
[Engine, SportsCar, new Provider(Car, {toAlias: SportsCar, multi: true})]);
var cars = injector.get(Car);
expect(cars.length).toEqual(1);
expect(cars[0]).toBe(injector.get(SportsCar));
});
it('should throw when the aliased binding does not exist', () => {
var injector = createInjector([bind('car').toAlias(SportsCar)]);
it('should throw when the aliased provider does not exist', () => {
var injector = createInjector([provide('car', {asAlias: SportsCar})]);
var e = `No provider for ${stringify(SportsCar)}! (car -> ${stringify(SportsCar)})`;
expect(() => injector.get('car')).toThrowError(e);
});
it('should throw with a meaningful message when the aliased binding is blank', () => {
expect(() => bind('car').toAlias(null)).toThrowError('Can not alias car to a blank value!');
});
it('should handle forwardRef in toAlias', () => {
var injector = createInjector([
bind('originalEngine')
.toClass(forwardRef(() => Engine)),
bind('aliasedEngine').toAlias(<any>forwardRef(() => 'originalEngine'))
provide('originalEngine', {asClass: forwardRef(() => Engine)}),
provide('aliasedEngine', {asAlias:<any>forwardRef(() => 'originalEngine')})
]);
expect(injector.get('aliasedEngine')).toBeAnInstanceOf(Engine);
});
it('should support overriding factory dependencies', () => {
var injector =
createInjector([Engine, bind(Car).toFactory((e) => new SportsCar(e), [Engine])]);
var injector = createInjector(
[Engine, provide(Car, {asFactory: (e) => new SportsCar(e), deps: [Engine]})]);
var car = injector.get(Car);
expect(car).toBeAnInstanceOf(SportsCar);
@ -248,33 +243,30 @@ export function main() {
expect(car.engine).toEqual(null);
});
it("should flatten passed-in bindings", () => {
it("should flatten passed-in providers", () => {
var injector = createInjector([[[Engine, Car]]]);
var car = injector.get(Car);
expect(car).toBeAnInstanceOf(Car);
});
it("should use the last binding when there are multiple bindings for same token", () => {
var injector =
createInjector([bind(Engine).toClass(Engine), bind(Engine).toClass(TurboEngine)]);
it("should use the last provider when there are multiple providers for same token", () => {
var injector = createInjector(
[provide(Engine, {asClass: Engine}), provide(Engine, {asClass: TurboEngine})]);
expect(injector.get(Engine)).toBeAnInstanceOf(TurboEngine);
});
it('should use non-type tokens', () => {
var injector = createInjector([bind('token').toValue('value')]);
var injector = createInjector([provide('token', {asValue: 'value'})]);
expect(injector.get('token')).toEqual('value');
});
it('should throw when given invalid bindings', () => {
it('should throw when given invalid providers', () => {
expect(() => createInjector(<any>["blah"]))
.toThrowError(
'Invalid binding - only instances of Binding and Type are allowed, got: blah');
expect(() => createInjector(<any>[bind("blah")]))
.toThrowError('Invalid binding - only instances of Binding and Type are allowed, ' +
'got: blah');
'Invalid provider - only instances of Provider and Type are allowed, got: blah');
});
it('should provide itself', () => {
@ -297,7 +289,7 @@ export function main() {
});
it('should throw when trying to instantiate a cyclic dependency', () => {
var injector = createInjector([Car, bind(Engine).toClass(CyclicEngine)]);
var injector = createInjector([Car, provide(Engine, {asClass: CyclicEngine})]);
expect(() => injector.get(Car))
.toThrowError(
@ -305,10 +297,10 @@ export function main() {
});
it('should show the full path when error happens in a constructor', () => {
var bindings = Injector.resolve([Car, bind(Engine).toClass(BrokenEngine)]);
var providers = Injector.resolve([Car, provide(Engine, {asClass: BrokenEngine})]);
var proto = new ProtoInjector([
new BindingWithVisibility(bindings[0], Visibility.Public),
new BindingWithVisibility(bindings[1], Visibility.Public)
new ProviderWithVisibility(providers[0], Visibility.Public),
new ProviderWithVisibility(providers[1], Visibility.Public)
]);
var injector = new Injector(proto, null, null);
@ -324,13 +316,13 @@ export function main() {
});
it('should provide context when throwing an exception ', () => {
var engineBinding = Injector.resolve([bind(Engine).toClass(BrokenEngine)])[0];
var engineProvider = Injector.resolve([provide(Engine, {asClass: BrokenEngine})])[0];
var protoParent =
new ProtoInjector([new BindingWithVisibility(engineBinding, Visibility.Public)]);
new ProtoInjector([new ProviderWithVisibility(engineProvider, Visibility.Public)]);
var carBinding = Injector.resolve([Car])[0];
var carProvider = Injector.resolve([Car])[0];
var protoChild =
new ProtoInjector([new BindingWithVisibility(carBinding, Visibility.Public)]);
new ProtoInjector([new ProviderWithVisibility(carProvider, Visibility.Public)]);
var parent = new Injector(protoParent, null, null, () => "parentContext");
var child = new Injector(protoChild, parent, null, () => "childContext");
@ -346,8 +338,10 @@ export function main() {
it('should instantiate an object after a failed attempt', () => {
var isBroken = true;
var injector = createInjector(
[Car, bind(Engine).toFactory(() => isBroken ? new BrokenEngine() : new Engine())]);
var injector = createInjector([
Car,
provide(Engine, {asFactory: (() => isBroken ? new BrokenEngine() : new Engine())})
]);
expect(() => injector.get(Car)).toThrowError(new RegExp("Error"));
@ -357,7 +351,7 @@ export function main() {
});
it('should support null values', () => {
var injector = createInjector([bind('null').toValue(null)]);
var injector = createInjector([provide('null', {asValue: null})]);
expect(injector.get('null')).toBe(null);
});
@ -367,14 +361,15 @@ export function main() {
var depProvider = <any>new SpyDependencyProvider();
depProvider.spy("getDependency").andReturn(e);
var bindings = Injector.resolve([Car]);
var proto = new ProtoInjector([new BindingWithVisibility(bindings[0], Visibility.Public)]);
var providers = Injector.resolve([Car]);
var proto =
new ProtoInjector([new ProviderWithVisibility(providers[0], Visibility.Public)]);
var injector = new Injector(proto, null, depProvider);
expect(injector.get(Car).engine).toEqual(e);
expect(depProvider.spy("getDependency"))
.toHaveBeenCalledWith(injector, bindings[0],
bindings[0].resolvedFactories[0].dependencies[0]);
.toHaveBeenCalledWith(injector, providers[0],
providers[0].resolvedFactories[0].dependencies[0]);
});
});
@ -390,10 +385,10 @@ export function main() {
expect(engineFromChild).toBe(engineFromParent);
});
it("should not use the child bindings when resolving the dependencies of a parent binding",
it("should not use the child providers when resolving the dependencies of a parent provider",
() => {
var parent = Injector.resolveAndCreate([Car, Engine]);
var child = parent.resolveAndCreateChild([bind(Engine).toClass(TurboEngine)]);
var child = parent.resolveAndCreateChild([provide(Engine, {asClass: TurboEngine})]);
var carFromChild = child.get(Car);
expect(carFromChild.engine).toBeAnInstanceOf(Engine);
@ -401,7 +396,7 @@ export function main() {
it('should create new instance in a child injector', () => {
var parent = Injector.resolveAndCreate([Engine]);
var child = parent.resolveAndCreateChild([bind(Engine).toClass(TurboEngine)]);
var child = parent.resolveAndCreateChild([provide(Engine, {asClass: TurboEngine})]);
var engineFromParent = parent.get(Engine);
var engineFromChild = child.get(Engine);
@ -444,16 +439,18 @@ export function main() {
describe("depedency resolution", () => {
describe("@Self()", () => {
it("should return a dependency from self", () => {
var inj = Injector.resolveAndCreate(
[Engine, bind(Car).toFactory((e) => new Car(e), [[Engine, new SelfMetadata()]])]);
var inj = Injector.resolveAndCreate([
Engine,
provide(Car, {asFactory: (e) => new Car(e), deps: [[Engine, new SelfMetadata()]]})
]);
expect(inj.get(Car)).toBeAnInstanceOf(Car);
});
it("should throw when not requested binding on self", () => {
it("should throw when not requested provider on self", () => {
var parent = Injector.resolveAndCreate([Engine]);
var child = parent.resolveAndCreateChild(
[bind(Car).toFactory((e) => new Car(e), [[Engine, new SelfMetadata()]])]);
[provide(Car, {asFactory: (e) => new Car(e), deps: [[Engine, new SelfMetadata()]]})]);
expect(() => child.get(Car))
.toThrowError(`No provider for Engine! (${stringify(Car)} -> ${stringify(Engine)})`);
@ -464,7 +461,7 @@ export function main() {
it("should return a dependency from same host", () => {
var parent = Injector.resolveAndCreate([Engine]);
var child = parent.resolveAndCreateChild(
[bind(Car).toFactory((e) => new Car(e), [[Engine, new HostMetadata()]])]);
[provide(Car, {asFactory: (e) => new Car(e), deps: [[Engine, new HostMetadata()]]})]);
expect(child.get(Car)).toBeAnInstanceOf(Car);
});
@ -472,11 +469,11 @@ export function main() {
it("should return a private dependency declared at the host", () => {
var engine = Injector.resolve([Engine])[0];
var protoParent =
new ProtoInjector([new BindingWithVisibility(engine, Visibility.Private)]);
new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Private)]);
var parent = new Injector(protoParent);
var child = Injector.resolveAndCreate(
[bind(Car).toFactory((e) => new Car(e), [[Engine, new HostMetadata()]])]);
[provide(Car, {asFactory: (e) => new Car(e), deps: [[Engine, new HostMetadata()]]})]);
child.internalStrategy.attach(parent, true); // host
@ -486,11 +483,11 @@ export function main() {
it("should not return a public dependency declared at the host", () => {
var engine = Injector.resolve([Engine])[0];
var protoParent =
new ProtoInjector([new BindingWithVisibility(engine, Visibility.Public)]);
new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Public)]);
var parent = new Injector(protoParent);
var child = Injector.resolveAndCreate(
[bind(Car).toFactory((e) => new Car(e), [[Engine, new HostMetadata()]])]);
[provide(Car, {asFactory: (e) => new Car(e), deps: [[Engine, new HostMetadata()]]})]);
child.internalStrategy.attach(parent, true); // host
@ -501,9 +498,8 @@ export function main() {
it("should not skip self", () => {
var parent = Injector.resolveAndCreate([Engine]);
var child = parent.resolveAndCreateChild([
bind(Engine)
.toClass(TurboEngine),
bind(Car).toFactory((e) => new Car(e), [[Engine, new HostMetadata()]])
provide(Engine, {asClass: TurboEngine}),
provide(Car, {asFactory: (e) => new Car(e), deps: [[Engine, new HostMetadata()]]})
]);
expect(child.get(Car).engine).toBeAnInstanceOf(TurboEngine);
@ -514,13 +510,13 @@ export function main() {
it("should return a private dependency declared at the host", () => {
var engine = Injector.resolve([Engine])[0];
var protoParent =
new ProtoInjector([new BindingWithVisibility(engine, Visibility.Private)]);
new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Private)]);
var parent = new Injector(protoParent);
var child = Injector.resolveAndCreate([
bind(Engine)
.toClass(BrokenEngine),
bind(Car).toFactory((e) => new Car(e), [[Engine, new SkipSelfMetadata()]])
provide(Engine, {asClass: BrokenEngine}),
provide(Car,
{asFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]})
]);
child.internalStrategy.attach(parent, true); // boundary
@ -530,13 +526,13 @@ export function main() {
it("should return a public dependency declared at the host", () => {
var engine = Injector.resolve([Engine])[0];
var protoParent =
new ProtoInjector([new BindingWithVisibility(engine, Visibility.Public)]);
new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Public)]);
var parent = new Injector(protoParent);
var child = Injector.resolveAndCreate([
bind(Engine)
.toClass(BrokenEngine),
bind(Car).toFactory((e) => new Car(e), [[Engine, new SkipSelfMetadata()]])
provide(Engine, {asClass: BrokenEngine}),
provide(Car,
{asFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]})
]);
child.internalStrategy.attach(parent, true); // boundary
@ -546,13 +542,13 @@ export function main() {
it("should not return a private dependency declared NOT at the host", () => {
var engine = Injector.resolve([Engine])[0];
var protoParent =
new ProtoInjector([new BindingWithVisibility(engine, Visibility.Private)]);
new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Private)]);
var parent = new Injector(protoParent);
var child = Injector.resolveAndCreate([
bind(Engine)
.toClass(BrokenEngine),
bind(Car).toFactory((e) => new Car(e), [[Engine, new SkipSelfMetadata()]])
provide(Engine, {asClass: BrokenEngine}),
provide(Car,
{asFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]})
]);
child.internalStrategy.attach(parent, false);
@ -563,9 +559,8 @@ export function main() {
it("should not skip self", () => {
var parent = Injector.resolveAndCreate([Engine]);
var child = parent.resolveAndCreateChild([
bind(Engine)
.toClass(TurboEngine),
bind(Car).toFactory((e) => new Car(e), [Engine])
provide(Engine, {asClass: TurboEngine}),
provide(Car, {asFactory: (e) => new Car(e), deps: [Engine]})
]);
expect(child.get(Car).engine).toBeAnInstanceOf(TurboEngine);
@ -575,70 +570,73 @@ export function main() {
describe('resolve', () => {
it('should resolve and flatten', () => {
var bindings = Injector.resolve([Engine, [BrokenEngine]]);
bindings.forEach(function(b) {
var providers = Injector.resolve([Engine, [BrokenEngine]]);
providers.forEach(function(b) {
if (isBlank(b)) return; // the result is a sparse array
expect(b instanceof ResolvedBinding_).toBe(true);
expect(b instanceof ResolvedProvider_).toBe(true);
});
});
it("should support multi bindings", () => {
var binding = Injector.resolve([
new Binding(Engine, {toClass: BrokenEngine, multi: true}),
new Binding(Engine, {toClass: TurboEngine, multi: true})
it("should support multi providers", () => {
var provider = Injector.resolve([
new Provider(Engine, {toClass: BrokenEngine, multi: true}),
new Provider(Engine, {toClass: TurboEngine, multi: true})
])[0];
expect(binding.key.token).toBe(Engine);
expect(binding.multiBinding).toEqual(true);
expect(binding.resolvedFactories.length).toEqual(2);
expect(provider.key.token).toBe(Engine);
expect(provider.multiProvider).toEqual(true);
expect(provider.resolvedFactories.length).toEqual(2);
});
it("should support multi bindings with only one binding", () => {
var binding =
Injector.resolve([new Binding(Engine, {toClass: BrokenEngine, multi: true})])[0];
it("should support multi providers with only one provider", () => {
var provider =
Injector.resolve([new Provider(Engine, {toClass: BrokenEngine, multi: true})])[0];
expect(binding.key.token).toBe(Engine);
expect(binding.multiBinding).toEqual(true);
expect(binding.resolvedFactories.length).toEqual(1);
expect(provider.key.token).toBe(Engine);
expect(provider.multiProvider).toEqual(true);
expect(provider.resolvedFactories.length).toEqual(1);
});
it("should throw when mixing multi bindings with regular bindings", () => {
it("should throw when mixing multi providers with regular providers", () => {
expect(() => {
Injector.resolve([new Binding(Engine, {toClass: BrokenEngine, multi: true}), Engine]);
}).toThrowErrorWith("Cannot mix multi bindings and regular bindings");
Injector.resolve([new Provider(Engine, {toClass: BrokenEngine, multi: true}), Engine]);
}).toThrowErrorWith("Cannot mix multi providers and regular providers");
expect(() => {
Injector.resolve([Engine, new Binding(Engine, {toClass: BrokenEngine, multi: true})]);
}).toThrowErrorWith("Cannot mix multi bindings and regular bindings");
Injector.resolve([Engine, new Provider(Engine, {toClass: BrokenEngine, multi: true})]);
}).toThrowErrorWith("Cannot mix multi providers and regular providers");
});
it('should resolve forward references', () => {
var bindings = Injector.resolve([
var providers = Injector.resolve([
forwardRef(() => Engine),
[bind(forwardRef(() => BrokenEngine)).toClass(forwardRef(() => Engine))],
bind(forwardRef(() => String)).toFactory(() => 'OK', [forwardRef(() => Engine)])
[provide(forwardRef(() => BrokenEngine), {asClass: forwardRef(() => Engine)})],
provide(forwardRef(() => String),
{asFactory: () => 'OK', deps: [forwardRef(() => Engine)]})
]);
var engineBinding = bindings[0];
var brokenEngineBinding = bindings[1];
var stringBinding = bindings[2];
var engineProvider = providers[0];
var brokenEngineProvider = providers[1];
var stringProvider = providers[2];
expect(engineBinding.resolvedFactories[0].factory() instanceof Engine).toBe(true);
expect(brokenEngineBinding.resolvedFactories[0].factory() instanceof Engine).toBe(true);
expect(stringBinding.resolvedFactories[0].dependencies[0].key).toEqual(Key.get(Engine));
expect(engineProvider.resolvedFactories[0].factory() instanceof Engine).toBe(true);
expect(brokenEngineProvider.resolvedFactories[0].factory() instanceof Engine).toBe(true);
expect(stringProvider.resolvedFactories[0].dependencies[0].key).toEqual(Key.get(Engine));
});
it('should support overriding factory dependencies with dependency annotations', () => {
var bindings = Injector.resolve([
bind("token")
.toFactory((e) => "result",
[[new InjectMetadata("dep"), new CustomDependencyMetadata()]])
var providers = Injector.resolve([
provide("token",
{
asFactory: (e) => "result",
deps: [[new InjectMetadata("dep"), new CustomDependencyMetadata()]]
})
]);
var binding = bindings[0];
var provider = providers[0];
expect(binding.resolvedFactories[0].dependencies[0].key.token).toEqual("dep");
expect(binding.resolvedFactories[0].dependencies[0].properties)
expect(provider.resolvedFactories[0].dependencies[0].key.token).toEqual("dep");
expect(provider.resolvedFactories[0].dependencies[0].properties)
.toEqual([new CustomDependencyMetadata()]);
});
});
@ -646,7 +644,7 @@ export function main() {
describe("displayName", () => {
it("should work", () => {
expect(Injector.resolveAndCreate([Engine, BrokenEngine]).displayName)
.toEqual('Injector(bindings: [ "Engine" , "BrokenEngine" ])');
.toEqual('Injector(providers: [ "Engine" , "BrokenEngine" ])');
});
});
});

View File

@ -15,7 +15,7 @@ import {
xit,
} from 'angular2/test_lib';
import {ListWrapper, StringMapWrapper} from 'angular2/src/core/facade/collection';
import {Component, View, NgFor, bind} from 'angular2/angular2';
import {Component, View, NgFor, provide} from 'angular2/angular2';
import {NgClass} from 'angular2/src/core/directives/ng_class';
import {APP_VIEW_POOL_CAPACITY} from 'angular2/src/core/linker/view_pool';
@ -29,7 +29,7 @@ export function main() {
describe('binding to CSS class list', () => {
describe('viewpool support', () => {
beforeEachBindings(() => { return [bind(APP_VIEW_POOL_CAPACITY).toValue(100)]; });
beforeEachBindings(() => { return [provide(APP_VIEW_POOL_CAPACITY, {asValue: 100})]; });
it('should clean up when the directive is destroyed',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {

View File

@ -12,6 +12,7 @@ import {
} from 'angular2/test_lib';
import {
bind,
provide,
forwardRef,
resolveForwardRef,
Component,
@ -39,7 +40,7 @@ export function main() {
});
}
@Component({selector: 'app', viewBindings: [forwardRef(() => Frame)]})
@Component({selector: 'app', viewProviders: [forwardRef(() => Frame)]})
@View({
template: `<door><lock></lock></door>`,
directives: [forwardRef(() => Door), forwardRef(() => Lock)]

View File

@ -13,7 +13,7 @@ import {
beforeEachBindings
} from 'angular2/test_lib';
import {Component, View, bind} from 'angular2/core';
import {Component, View, provide} from 'angular2/core';
import {SpyProtoViewFactory} from '../spies';
import {
CompiledHostTemplate,
@ -37,10 +37,10 @@ export function main() {
protoViewFactorySpy = new SpyProtoViewFactory();
someProtoView = new AppProtoView(null, null, null, null, null, null);
protoViewFactorySpy.spy('createHost').andReturn(someProtoView);
var factoryBinding = bind(ProtoViewFactory).toValue(protoViewFactorySpy);
var classBinding = bind(Compiler).toClass(Compiler_);
var bindings = [factoryBinding, classBinding];
return bindings;
var factory = provide(ProtoViewFactory, {asValue: protoViewFactorySpy});
var classProvider = provide(Compiler, {asClass: Compiler_});
var providers = [factory, classProvider];
return providers;
});
beforeEach(inject([Compiler], (_compiler) => {

View File

@ -47,8 +47,6 @@ class SomeDirectiveWithProperties {
class SomeDirectiveWithEvents {
}
@Directive({selector: 'someDirective'})
class SomeDirectiveWithSetterProps {
@Input("renamed")
@ -143,11 +141,6 @@ export function main() {
expect(directiveMetadata.inputs).toEqual(['a: renamed']);
});
it('should use properties as inputs', () => {
var directiveMetadata = resolver.resolve(SomeDirectiveWithProperties);
expect(directiveMetadata.inputs).toEqual(['a']);
});
});
describe('outputs', () => {
@ -160,11 +153,6 @@ export function main() {
var directiveMetadata = resolver.resolve(SomeDirectiveWithGetterOutputs);
expect(directiveMetadata.outputs).toEqual(['a: renamed']);
});
it('should use events as outputs', () => {
var directiveMetadata = resolver.resolve(SomeDirectiveWithEvents);
expect(directiveMetadata.outputs).toEqual(['a']);
});
});
describe('host', () => {

View File

@ -270,7 +270,7 @@ class ChildComp {
class DynamicallyCreatedComponentService {}
@Component({selector: 'hello-cmp', viewBindings: [DynamicallyCreatedComponentService]})
@Component({selector: 'hello-cmp', viewProviders: [DynamicallyCreatedComponentService]})
@View({template: "{{greeting}}"})
class DynamicallyCreatedCmp implements OnDestroy {
greeting: string;

View File

@ -27,7 +27,7 @@ import {
ProtoElementInjector,
ElementInjector,
PreBuiltObjects,
DirectiveBinding,
DirectiveProvider,
TreeNode
} from 'angular2/src/core/linker/element_injector';
import {
@ -38,7 +38,7 @@ import {
DirectiveMetadata
} from 'angular2/src/core/metadata';
import {OnDestroy} from 'angular2/lifecycle_hooks';
import {bind, Injector, Binding, Optional, Inject, Injectable, Self, SkipSelf, InjectMetadata, Host, HostMetadata, SkipSelfMetadata} from 'angular2/core';
import {provide, Injector, Provider, Optional, Inject, Injectable, Self, SkipSelf, InjectMetadata, Host, HostMetadata, SkipSelfMetadata} from 'angular2/core';
import {ViewContainerRef, ViewContainerRef_} from 'angular2/src/core/linker/view_container_ref';
import {TemplateRef, TemplateRef_} from 'angular2/src/core/linker/template_ref';
import {ElementRef} from 'angular2/src/core/linker/element_ref';
@ -228,25 +228,25 @@ class DirectiveWithDestroy implements OnDestroy {
export function main() {
var defaultPreBuiltObjects = new PreBuiltObjects(null, createDummyView(), <any>new SpyElementRef(), null);
// An injector with more than 10 bindings will switch to the dynamic strategy
var dynamicBindings = [];
// An injector with more than 10 providers will switch to the dynamic strategy
var dynamicProviders = [];
for (var i = 0; i < 20; i++) {
dynamicBindings.push(bind(i).toValue(i));
dynamicProviders.push(provide(i, {asValue: i}));
}
function createPei(parent, index, bindings: any[], distance = 1, hasShadowRoot = false, dirVariableBindings = null) {
var directiveBinding = bindings.map(b => {
if (b instanceof DirectiveBinding) return b;
if (b instanceof Binding) return DirectiveBinding.createFromBinding(b, null);
return DirectiveBinding.createFromType(b, null);
function createPei(parent, index, providers: any[], distance = 1, hasShadowRoot = false, dirVariableBindings = null) {
var directiveProvider = providers.map(b => {
if (b instanceof DirectiveProvider) return b;
if (b instanceof Provider) return DirectiveProvider.createFromProvider(b, null);
return DirectiveProvider.createFromType(b, null);
});
return ProtoElementInjector.create(parent, index, directiveBinding, hasShadowRoot, distance, dirVariableBindings);
return ProtoElementInjector.create(parent, index, directiveProvider, hasShadowRoot, distance, dirVariableBindings);
}
function injector(bindings, imperativelyCreatedInjector = null, isComponent: boolean = false,
function injector(providers, imperativelyCreatedInjector = null, isComponent: boolean = false,
preBuiltObjects = null, attributes = null, dirVariableBindings = null) {
var proto = createPei(null, 0, bindings, 0, isComponent, dirVariableBindings);
var proto = createPei(null, 0, providers, 0, isComponent, dirVariableBindings);
proto.attributes = attributes;
var inj = proto.instantiate(null);
@ -255,28 +255,28 @@ export function main() {
return inj;
}
function parentChildInjectors(parentBindings, childBindings, parentPreBuildObjects = null, imperativelyCreatedInjector = null) {
function parentChildInjectors(parentProviders, childProviders, parentPreBuildObjects = null, imperativelyCreatedInjector = null) {
if (isBlank(parentPreBuildObjects)) parentPreBuildObjects = defaultPreBuiltObjects;
var protoParent = createPei(null, 0, parentBindings);
var protoParent = createPei(null, 0, parentProviders);
var parent = protoParent.instantiate(null);
parent.hydrate(null, null, parentPreBuildObjects);
var protoChild = createPei(protoParent, 1, childBindings, 1, false);
var protoChild = createPei(protoParent, 1, childProviders, 1, false);
var child = protoChild.instantiate(parent);
child.hydrate(imperativelyCreatedInjector, null, defaultPreBuiltObjects);
return child;
}
function hostShadowInjectors(hostBindings: any[],
shadowBindings: any[], imperativelyCreatedInjector = null): ElementInjector {
var protoHost = createPei(null, 0, hostBindings, 0, true);
function hostShadowInjectors(hostProviders: any[],
shadowProviders: any[], imperativelyCreatedInjector = null): ElementInjector {
var protoHost = createPei(null, 0, hostProviders, 0, true);
var host = protoHost.instantiate(null);
host.hydrate(null, null, defaultPreBuiltObjects);
var protoShadow = createPei(null, 0, shadowBindings, 0, false);
var protoShadow = createPei(null, 0, shadowProviders, 0, false);
var shadow = protoShadow.instantiate(null);
shadow.hydrate(imperativelyCreatedInjector, host, null);
@ -321,33 +321,33 @@ export function main() {
});
describe('inline strategy', () => {
it("should allow for direct access using getBindingAtIndex", () => {
var proto = createPei(null, 0, [bind(SimpleDirective).toClass(SimpleDirective)]);
it("should allow for direct access using getProviderAtIndex", () => {
var proto = createPei(null, 0, [provide(SimpleDirective, {asClass: SimpleDirective})]);
expect(proto.getBindingAtIndex(0)).toBeAnInstanceOf(DirectiveBinding);
expect(() => proto.getBindingAtIndex(-1)).toThrowError('Index -1 is out-of-bounds.');
expect(() => proto.getBindingAtIndex(10)).toThrowError('Index 10 is out-of-bounds.');
expect(proto.getProviderAtIndex(0)).toBeAnInstanceOf(DirectiveProvider);
expect(() => proto.getProviderAtIndex(-1)).toThrowError('Index -1 is out-of-bounds.');
expect(() => proto.getProviderAtIndex(10)).toThrowError('Index 10 is out-of-bounds.');
});
});
describe('dynamic strategy', () => {
it("should allow for direct access using getBindingAtIndex", () => {
var proto = createPei(null, 0, dynamicBindings);
it("should allow for direct access using getProviderAtIndex", () => {
var proto = createPei(null, 0, dynamicProviders);
expect(proto.getBindingAtIndex(0)).toBeAnInstanceOf(DirectiveBinding);
expect(() => proto.getBindingAtIndex(-1)).toThrowError('Index -1 is out-of-bounds.');
expect(() => proto.getBindingAtIndex(dynamicBindings.length - 1)).not.toThrow();
expect(() => proto.getBindingAtIndex(dynamicBindings.length))
.toThrowError(`Index ${dynamicBindings.length} is out-of-bounds.`);
expect(proto.getProviderAtIndex(0)).toBeAnInstanceOf(DirectiveProvider);
expect(() => proto.getProviderAtIndex(-1)).toThrowError('Index -1 is out-of-bounds.');
expect(() => proto.getProviderAtIndex(dynamicProviders.length - 1)).not.toThrow();
expect(() => proto.getProviderAtIndex(dynamicProviders.length))
.toThrowError(`Index ${dynamicProviders.length} is out-of-bounds.`);
});
});
describe('event emitters', () => {
it('should return a list of event accessors', () => {
var binding = DirectiveBinding.createFromType(HasEventEmitter,
var provider = DirectiveProvider.createFromType(HasEventEmitter,
new DirectiveMetadata({outputs: ['emitter']}));
var inj = createPei(null, 0, [binding]);
var inj = createPei(null, 0, [provider]);
expect(inj.eventEmitterAccessors.length).toEqual(1);
var accessor = inj.eventEmitterAccessors[0][0];
@ -356,10 +356,10 @@ export function main() {
});
it('should allow a different event vs field name', () => {
var binding = DirectiveBinding.createFromType(HasEventEmitter,
var provider = DirectiveProvider.createFromType(HasEventEmitter,
new DirectiveMetadata({outputs: ['emitter: publicEmitter']}));
var inj = createPei(null, 0, [binding]);
var inj = createPei(null, 0, [provider]);
expect(inj.eventEmitterAccessors.length).toEqual(1);
var accessor = inj.eventEmitterAccessors[0][0];
@ -369,53 +369,53 @@ export function main() {
});
describe(".create", () => {
it("should collect bindings from all directives", () => {
it("should collect providers from all directives", () => {
var pei = createPei(null, 0, [
DirectiveBinding.createFromType(
DirectiveProvider.createFromType(
SimpleDirective,
new ComponentMetadata({bindings: [bind('injectable1').toValue('injectable1')]})),
DirectiveBinding.createFromType(SomeOtherDirective, new ComponentMetadata({
bindings: [bind('injectable2').toValue('injectable2')]
new ComponentMetadata({providers: [provide('injectable1', {asValue: 'injectable1'})]})),
DirectiveProvider.createFromType(SomeOtherDirective, new ComponentMetadata({
providers: [provide('injectable2', {asValue: 'injectable2'})]
}))
]);
expect(pei.getBindingAtIndex(0).key.token).toBe(SimpleDirective);
expect(pei.getBindingAtIndex(1).key.token).toBe(SomeOtherDirective);
expect(pei.getBindingAtIndex(2).key.token).toEqual("injectable1");
expect(pei.getBindingAtIndex(3).key.token).toEqual("injectable2");
expect(pei.getProviderAtIndex(0).key.token).toBe(SimpleDirective);
expect(pei.getProviderAtIndex(1).key.token).toBe(SomeOtherDirective);
expect(pei.getProviderAtIndex(2).key.token).toEqual("injectable1");
expect(pei.getProviderAtIndex(3).key.token).toEqual("injectable2");
});
it("should collect view bindings from the component", () => {
it("should collect view providers from the component", () => {
var pei = createPei(null, 0,
[DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata({
viewBindings: [bind('injectable1').toValue('injectable1')]
[DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata({
viewProviders: [provide('injectable1', {asValue: 'injectable1'})]
}))],
0, true);
expect(pei.getBindingAtIndex(0).key.token).toBe(SimpleDirective);
expect(pei.getBindingAtIndex(1).key.token).toEqual("injectable1");
expect(pei.getProviderAtIndex(0).key.token).toBe(SimpleDirective);
expect(pei.getProviderAtIndex(1).key.token).toEqual("injectable1");
});
it("should flatten nested arrays", () => {
var pei = createPei(null, 0, [
DirectiveBinding.createFromType(
DirectiveProvider.createFromType(
SimpleDirective,
new ComponentMetadata({
viewBindings: [[[bind('view').toValue('view')]]],
bindings: [[[bind('host').toValue('host')]]]
viewProviders: [[[provide('view', {asValue: 'view'})]]],
providers: [[[provide('host', {asValue: 'host'})]]]
}))
], 0, true);
expect(pei.getBindingAtIndex(0).key.token).toBe(SimpleDirective);
expect(pei.getBindingAtIndex(1).key.token).toEqual("view");
expect(pei.getBindingAtIndex(2).key.token).toEqual("host");
expect(pei.getProviderAtIndex(0).key.token).toBe(SimpleDirective);
expect(pei.getProviderAtIndex(1).key.token).toEqual("view");
expect(pei.getProviderAtIndex(2).key.token).toEqual("host");
});
it('should support an arbitrary number of bindings', () => {
var pei = createPei(null, 0, dynamicBindings);
it('should support an arbitrary number of providers', () => {
var pei = createPei(null, 0, dynamicProviders);
for (var i = 0; i < dynamicBindings.length; i++) {
expect(pei.getBindingAtIndex(i).key.token).toBe(i);
for (var i = 0; i < dynamicProviders.length; i++) {
expect(pei.getProviderAtIndex(i).key.token).toBe(i);
}
});
});
@ -463,7 +463,7 @@ export function main() {
});
describe("hasBindings", () => {
it("should be true when there are bindings", () => {
it("should be true when there are providers", () => {
var p = createPei(null, 0, [SimpleDirective]);
expect(p.hasBindings).toBeTruthy();
});
@ -482,22 +482,22 @@ export function main() {
() => { expect(injector([SimpleDirective]).hasInstances()).toBe(true); });
});
[{ strategy: 'inline', bindings: [] }, { strategy: 'dynamic',
bindings: dynamicBindings }].forEach((context) => {
[{ strategy: 'inline', providers: [] }, { strategy: 'dynamic',
providers: dynamicProviders }].forEach((context) => {
var extraBindings = context['bindings'];
var extraProviders = context['providers'];
describe(`${context['strategy']} strategy`, () => {
describe("hydrate", () => {
it("should instantiate directives that have no dependencies", () => {
var bindings = ListWrapper.concat([SimpleDirective], extraBindings);
var inj = injector(bindings);
var providers = ListWrapper.concat([SimpleDirective], extraProviders);
var inj = injector(providers);
expect(inj.get(SimpleDirective)).toBeAnInstanceOf(SimpleDirective);
});
it("should instantiate directives that depend on an arbitrary number of directives", () => {
var bindings = ListWrapper.concat([SimpleDirective, NeedsDirective], extraBindings);
var inj = injector(bindings);
var providers = ListWrapper.concat([SimpleDirective, NeedsDirective], extraProviders);
var inj = injector(providers);
var d = inj.get(NeedsDirective);
@ -505,80 +505,74 @@ export function main() {
expect(d.dependency).toBeAnInstanceOf(SimpleDirective);
});
it("should instantiate bindings that have dependencies with set visibility",
it("should instantiate providers that have dependencies with set visibility",
function() {
var childInj = parentChildInjectors(
ListWrapper.concat(
[DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata({
bindings: [bind('injectable1').toValue('injectable1')]
[DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata({
providers: [provide('injectable1', {asValue: 'injectable1'})]
}))],
extraBindings),
[DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata({
bindings: [
bind('injectable1')
.toValue('new-injectable1'),
bind('injectable2')
.toFactory(
extraProviders),
[DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata({
providers: [
provide('injectable1', {asValue:'new-injectable1'}),
provide('injectable2', {asFactory:
(val) => `${val}-injectable2`,
[[new InjectMetadata('injectable1'), new SkipSelfMetadata()]])
deps: [[new InjectMetadata('injectable1'), new SkipSelfMetadata()]]})
]
}))]);
expect(childInj.get('injectable2')).toEqual('injectable1-injectable2');
});
it("should instantiate bindings that have dependencies", () => {
var bindings = [
bind('injectable1')
.toValue('injectable1'),
bind('injectable2')
.toFactory(
it("should instantiate providers that have dependencies", () => {
var providers = [
provide('injectable1', {asValue: 'injectable1'}),
provide('injectable2', {asFactory:
(val) => `${val}-injectable2`,
['injectable1'])
deps: ['injectable1']})
];
var inj = injector(ListWrapper.concat(
[DirectiveBinding.createFromType(SimpleDirective,
new DirectiveMetadata({bindings: bindings}))],
extraBindings));
[DirectiveProvider.createFromType(SimpleDirective,
new DirectiveMetadata({providers: providers}))],
extraProviders));
expect(inj.get('injectable2')).toEqual('injectable1-injectable2');
});
it("should instantiate viewBindings that have dependencies", () => {
var viewBindings = [
bind('injectable1')
.toValue('injectable1'),
bind('injectable2')
.toFactory(
(val) => `${val}-injectable2`,
['injectable1'])
it("should instantiate viewProviders that have dependencies", () => {
var viewProviders = [
provide('injectable1', {asValue: 'injectable1'}),
provide('injectable2', {asFactory:
(val) => `${val}-injectable2`,
deps: ['injectable1']})
];
var inj = injector(ListWrapper.concat(
[DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata({
viewBindings: viewBindings}))], extraBindings),
[DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata({
viewProviders: viewProviders}))], extraProviders),
null, true);
expect(inj.get('injectable2')).toEqual('injectable1-injectable2');
});
it("should instantiate components that depend on viewBindings bindings", () => {
it("should instantiate components that depend on viewProviders providers", () => {
var inj = injector(
ListWrapper.concat([DirectiveBinding.createFromType(NeedsService, new ComponentMetadata({
viewBindings: [bind('service').toValue('service')]
ListWrapper.concat([DirectiveProvider.createFromType(NeedsService, new ComponentMetadata({
viewProviders: [provide('service', {asValue: 'service'})]
}))],
extraBindings),
extraProviders),
null, true);
expect(inj.get(NeedsService).service).toEqual('service');
});
it("should instantiate bindings lazily", () => {
it("should instantiate providers lazily", () => {
var created = false;
var inj = injector(
ListWrapper.concat([DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata({
bindings: [bind('service').toFactory(() => created = true)]
ListWrapper.concat([DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata({
providers: [provide('service', {asFactory: () => created = true})]
}))],
extraBindings),
extraProviders),
null, true);
expect(created).toBe(false);
@ -588,13 +582,13 @@ export function main() {
expect(created).toBe(true);
});
it("should instantiate view bindings lazily", () => {
it("should instantiate view providers lazily", () => {
var created = false;
var inj = injector(
ListWrapper.concat([DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata({
viewBindings: [bind('service').toFactory(() => created = true)]
ListWrapper.concat([DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata({
viewProviders: [provide('service', {asFactory: () => created = true})]
}))],
extraBindings),
extraProviders),
null, true);
expect(created).toBe(false);
@ -604,31 +598,31 @@ export function main() {
expect(created).toBe(true);
});
it("should not instantiate other directives that depend on viewBindings bindings",
it("should not instantiate other directives that depend on viewProviders providers",
() => {
var directiveAnnotation = new ComponentMetadata({
viewBindings: ListWrapper.concat([bind("service").toValue("service")], extraBindings)
viewProviders: ListWrapper.concat([provide("service", {asValue: "service"})], extraProviders)
});
var componentDirective =
DirectiveBinding.createFromType(SimpleDirective, directiveAnnotation);
DirectiveProvider.createFromType(SimpleDirective, directiveAnnotation);
expect(() => { injector([componentDirective, NeedsService], null); })
.toThrowError(containsRegexp(
`No provider for service! (${stringify(NeedsService) } -> service)`));
});
it("should instantiate directives that depend on bindings of other directives", () => {
it("should instantiate directives that depend on providers of other directives", () => {
var shadowInj = hostShadowInjectors(
ListWrapper.concat([DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata({
bindings: [bind('service').toValue('hostService')]})
)], extraBindings),
ListWrapper.concat([NeedsService], extraBindings)
ListWrapper.concat([DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata({
providers: [provide('service', {asValue: 'hostService'})]})
)], extraProviders),
ListWrapper.concat([NeedsService], extraProviders)
);
expect(shadowInj.get(NeedsService).service).toEqual('hostService');
});
it("should instantiate directives that depend on imperatively created injector bindings (bootstrap)", () => {
it("should instantiate directives that depend on imperatively created injector providers (bootstrap)", () => {
var imperativelyCreatedInjector = Injector.resolveAndCreate([
bind("service").toValue('appService')
provide("service", {asValue: 'appService'})
]);
var inj = injector([NeedsService], imperativelyCreatedInjector);
expect(inj.get(NeedsService).service).toEqual('appService');
@ -636,81 +630,81 @@ export function main() {
expect(() => injector([NeedsServiceFromHost], imperativelyCreatedInjector)).toThrowError();
});
it("should instantiate directives that depend on imperatively created injector bindings (root injector)", () => {
it("should instantiate directives that depend on imperatively created injector providers (root injector)", () => {
var imperativelyCreatedInjector = Injector.resolveAndCreate([
bind("service").toValue('appService')
provide("service", {asValue: 'appService'})
]);
var inj = hostShadowInjectors([SimpleDirective], [NeedsService, NeedsServiceFromHost], imperativelyCreatedInjector);
expect(inj.get(NeedsService).service).toEqual('appService');
expect(inj.get(NeedsServiceFromHost).service).toEqual('appService');
});
it("should instantiate directives that depend on imperatively created injector bindings (child injector)", () => {
it("should instantiate directives that depend on imperatively created injector providers (child injector)", () => {
var imperativelyCreatedInjector = Injector.resolveAndCreate([
bind("service").toValue('appService')
provide("service", {asValue: 'appService'})
]);
var inj = parentChildInjectors([], [NeedsService, NeedsServiceFromHost], null, imperativelyCreatedInjector);
expect(inj.get(NeedsService).service).toEqual('appService');
expect(inj.get(NeedsServiceFromHost).service).toEqual('appService');
});
it("should prioritize viewBindings over bindings for the same binding", () => {
it("should prioritize viewProviders over providers for the same provider", () => {
var inj = injector(
ListWrapper.concat([DirectiveBinding.createFromType(NeedsService, new ComponentMetadata({
bindings: [bind('service').toValue('hostService')],
viewBindings: [bind('service').toValue('viewService')]})
)], extraBindings), null, true);
ListWrapper.concat([DirectiveProvider.createFromType(NeedsService, new ComponentMetadata({
providers: [provide('service', {asValue: 'hostService'})],
viewProviders: [provide('service', {asValue: 'viewService'})]})
)], extraProviders), null, true);
expect(inj.get(NeedsService).service).toEqual('viewService');
});
it("should prioritize directive bindings over component bindings", () => {
var component = DirectiveBinding.createFromType(NeedsService, new ComponentMetadata({
bindings: [bind('service').toValue('compService')]}));
var directive = DirectiveBinding.createFromType(SomeOtherDirective, new DirectiveMetadata({
bindings: [bind('service').toValue('dirService')]}));
var inj = injector(ListWrapper.concat([component, directive], extraBindings), null, true);
it("should prioritize directive providers over component providers", () => {
var component = DirectiveProvider.createFromType(NeedsService, new ComponentMetadata({
providers: [provide('service', {asValue: 'compService'})]}));
var directive = DirectiveProvider.createFromType(SomeOtherDirective, new DirectiveMetadata({
providers: [provide('service', {asValue: 'dirService'})]}));
var inj = injector(ListWrapper.concat([component, directive], extraProviders), null, true);
expect(inj.get(NeedsService).service).toEqual('dirService');
});
it("should not instantiate a directive in a view that has a host dependency on bindings"+
it("should not instantiate a directive in a view that has a host dependency on providers"+
" of the component", () => {
expect(() => {
hostShadowInjectors(
ListWrapper.concat([
DirectiveBinding.createFromType(SomeOtherDirective, new DirectiveMetadata({
bindings: [bind('service').toValue('hostService')]})
)], extraBindings),
ListWrapper.concat([NeedsServiceFromHost], extraBindings)
DirectiveProvider.createFromType(SomeOtherDirective, new DirectiveMetadata({
providers: [provide('service', {asValue: 'hostService'})]})
)], extraProviders),
ListWrapper.concat([NeedsServiceFromHost], extraProviders)
);
}).toThrowError(new RegExp("No provider for service!"));
});
it("should not instantiate a directive in a view that has a host dependency on bindings"+
it("should not instantiate a directive in a view that has a host dependency on providers"+
" of a decorator directive", () => {
expect(() => {
hostShadowInjectors(
ListWrapper.concat([
SimpleDirective,
DirectiveBinding.createFromType(SomeOtherDirective, new DirectiveMetadata({
bindings: [bind('service').toValue('hostService')]})
)], extraBindings),
DirectiveProvider.createFromType(SomeOtherDirective, new DirectiveMetadata({
providers: [provide('service', {asValue: 'hostService'})]})
)], extraProviders),
ListWrapper.concat([NeedsServiceFromHost], extraBindings)
ListWrapper.concat([NeedsServiceFromHost], extraProviders)
);
}).toThrowError(new RegExp("No provider for service!"));
});
it("should instantiate directives that depend on pre built objects", () => {
var templateRef = new TemplateRef_(<any>new SpyElementRef());
var bindings = ListWrapper.concat([NeedsTemplateRef], extraBindings);
var inj = injector(bindings, null, false, new PreBuiltObjects(null, null, null, templateRef));
var providers = ListWrapper.concat([NeedsTemplateRef], extraProviders);
var inj = injector(providers, null, false, new PreBuiltObjects(null, null, null, templateRef));
expect(inj.get(NeedsTemplateRef).templateRef).toEqual(templateRef);
});
it("should get directives", () => {
var child = hostShadowInjectors(
ListWrapper.concat([SomeOtherDirective, SimpleDirective], extraBindings),
ListWrapper.concat([SomeOtherDirective, SimpleDirective], extraProviders),
[NeedsDirectiveFromHostShadowDom]);
var d = child.get(NeedsDirectiveFromHostShadowDom);
@ -720,7 +714,7 @@ export function main() {
});
it("should get directives from the host", () => {
var child = parentChildInjectors(ListWrapper.concat([SimpleDirective], extraBindings),
var child = parentChildInjectors(ListWrapper.concat([SimpleDirective], extraProviders),
[NeeedsDirectiveFromHost]);
var d = child.get(NeeedsDirectiveFromHost);
@ -730,30 +724,30 @@ export function main() {
});
it("should throw when a dependency cannot be resolved", () => {
expect(() => injector(ListWrapper.concat([NeeedsDirectiveFromHost], extraBindings)))
expect(() => injector(ListWrapper.concat([NeeedsDirectiveFromHost], extraProviders)))
.toThrowError(containsRegexp(
`No provider for ${stringify(SimpleDirective) }! (${stringify(NeeedsDirectiveFromHost) } -> ${stringify(SimpleDirective) })`));
});
it("should inject null when an optional dependency cannot be resolved", () => {
var inj = injector(ListWrapper.concat([OptionallyNeedsDirective], extraBindings));
var inj = injector(ListWrapper.concat([OptionallyNeedsDirective], extraProviders));
var d = inj.get(OptionallyNeedsDirective);
expect(d.dependency).toEqual(null);
});
it("should accept bindings instead of types", () => {
it("should accept providers instead of types", () => {
var inj = injector(
ListWrapper.concat([bind(SimpleDirective).toClass(SimpleDirective)], extraBindings));
ListWrapper.concat([provide(SimpleDirective, {asClass: SimpleDirective})], extraProviders));
expect(inj.get(SimpleDirective)).toBeAnInstanceOf(SimpleDirective);
});
it("should allow for direct access using getDirectiveAtIndex", () => {
var bindings =
ListWrapper.concat([bind(SimpleDirective).toClass(SimpleDirective)], extraBindings);
var providers =
ListWrapper.concat([provide(SimpleDirective, {asClass: SimpleDirective})], extraProviders);
var inj = injector(bindings);
var inj = injector(providers);
var firsIndexOut = bindings.length > 10 ? bindings.length : 10;
var firsIndexOut = providers.length > 10 ? providers.length : 10;
expect(inj.getDirectiveAtIndex(0)).toBeAnInstanceOf(SimpleDirective);
expect(() => inj.getDirectiveAtIndex(-1)).toThrowError('Index -1 is out-of-bounds.');
@ -762,9 +756,9 @@ export function main() {
});
it("should instantiate directives that depend on the containing component", () => {
var directiveBinding =
DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata());
var shadow = hostShadowInjectors(ListWrapper.concat([directiveBinding], extraBindings),
var directiveProvider =
DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata());
var shadow = hostShadowInjectors(ListWrapper.concat([directiveProvider], extraProviders),
[NeeedsDirectiveFromHost]);
var d = shadow.get(NeeedsDirectiveFromHost);
@ -774,12 +768,12 @@ export function main() {
it("should not instantiate directives that depend on other directives in the containing component's ElementInjector",
() => {
var directiveBinding =
DirectiveBinding.createFromType(SomeOtherDirective, new ComponentMetadata());
var directiveProvider =
DirectiveProvider.createFromType(SomeOtherDirective, new ComponentMetadata());
expect(() =>
{
hostShadowInjectors(
ListWrapper.concat([directiveBinding, SimpleDirective], extraBindings),
ListWrapper.concat([directiveProvider, SimpleDirective], extraProviders),
[NeedsDirective]);
})
.toThrowError(containsRegexp(
@ -789,12 +783,12 @@ export function main() {
describe("getRootViewInjectors", () => {
it("should return an empty array if there is no nested view", () => {
var inj = injector(extraBindings);
var inj = injector(extraProviders);
expect(inj.getRootViewInjectors()).toEqual([]);
});
it("should return an empty array on a dehydrated view", () => {
var inj = injector(extraBindings);
var inj = injector(extraProviders);
inj.dehydrate();
expect(inj.getRootViewInjectors()).toEqual([]);
});
@ -810,19 +804,19 @@ export function main() {
}
it("should handle repeated hydration / dehydration", () => {
var inj = injector(extraBindings);
var inj = injector(extraProviders);
cycleHydrate(inj);
});
it("should handle repeated hydration / dehydration with query present", () => {
var inj = injector(ListWrapper.concat([NeedsQuery], extraBindings));
var inj = injector(ListWrapper.concat([NeedsQuery], extraProviders));
cycleHydrate(inj);
});
it("should handle repeated hydration / dehydration with view query present", () => {
var inj = injector(extraBindings);
var host = injector(ListWrapper.concat([NeedsViewQuery], extraBindings));
var inj = injector(extraProviders);
var host = injector(ListWrapper.concat([NeedsViewQuery], extraProviders));
cycleHydrate(inj, host);
});
@ -831,9 +825,9 @@ export function main() {
describe("lifecycle", () => {
it("should call onDestroy on directives subscribed to this event", () => {
var inj = injector(ListWrapper.concat(
[DirectiveBinding.createFromType(DirectiveWithDestroy,
[DirectiveProvider.createFromType(DirectiveWithDestroy,
new DirectiveMetadata())],
extraBindings));
extraProviders));
var destroy = inj.get(DirectiveWithDestroy);
inj.dehydrate();
expect(destroy.onDestroyCounter).toBe(1);
@ -841,9 +835,9 @@ export function main() {
it("should work with services", () => {
var inj = injector(ListWrapper.concat(
[DirectiveBinding.createFromType(
SimpleDirective, new DirectiveMetadata({bindings: [SimpleService]}))],
extraBindings));
[DirectiveProvider.createFromType(
SimpleDirective, new DirectiveMetadata({providers: [SimpleService]}))],
extraProviders));
inj.dehydrate();
});
});
@ -854,7 +848,7 @@ export function main() {
attributes.set( 'type', 'text');
attributes.set( 'title', '');
var inj = injector(ListWrapper.concat([NeedsAttribute], extraBindings), null, false, null,
var inj = injector(ListWrapper.concat([NeedsAttribute], extraProviders), null, false, null,
attributes);
var needsAttribute = inj.get(NeedsAttribute);
@ -867,7 +861,7 @@ export function main() {
var attributes = new Map();
attributes.set( 'foo', 'bar');
var inj = injector(ListWrapper.concat([NeedsAttributeNoType], extraBindings), null, false,
var inj = injector(ListWrapper.concat([NeedsAttributeNoType], extraProviders), null, false,
null, attributes);
var needsAttribute = inj.get(NeedsAttributeNoType);
@ -877,7 +871,7 @@ export function main() {
describe("refs", () => {
it("should inject ElementRef", () => {
var inj = injector(ListWrapper.concat([NeedsElementRef], extraBindings));
var inj = injector(ListWrapper.concat([NeedsElementRef], extraProviders));
expect(inj.get(NeedsElementRef).elementRef).toBe(defaultPreBuiltObjects.elementRef);
});
@ -886,8 +880,8 @@ export function main() {
var view = <any>createDummyView();
var childView = createDummyView(cd);
view.spy('getNestedView').andReturn(childView);
var binding = DirectiveBinding.createFromType(ComponentNeedsChangeDetectorRef, new ComponentMetadata());
var inj = injector(ListWrapper.concat([binding], extraBindings), null, true,
var provider = DirectiveProvider.createFromType(ComponentNeedsChangeDetectorRef, new ComponentMetadata());
var inj = injector(ListWrapper.concat([provider], extraProviders), null, true,
new PreBuiltObjects(null, view, <any>new SpyElementRef(), null));
expect(inj.get(ComponentNeedsChangeDetectorRef).changeDetectorRef).toBe(cd.ref);
@ -896,34 +890,34 @@ export function main() {
it("should inject ChangeDetectorRef of the containing component into directives", () => {
var cd = new DynamicChangeDetector(null, null, 0, [], [], null, [], [], [], null);
var view = createDummyView(cd);
var binding = DirectiveBinding.createFromType(DirectiveNeedsChangeDetectorRef, new DirectiveMetadata());
var inj = injector(ListWrapper.concat([binding], extraBindings), null, false,
var provider = DirectiveProvider.createFromType(DirectiveNeedsChangeDetectorRef, new DirectiveMetadata());
var inj = injector(ListWrapper.concat([provider], extraProviders), null, false,
new PreBuiltObjects(null, view, <any>new SpyElementRef(), null));
expect(inj.get(DirectiveNeedsChangeDetectorRef).changeDetectorRef).toBe(cd.ref);
});
it('should inject ViewContainerRef', () => {
var inj = injector(ListWrapper.concat([NeedsViewContainer], extraBindings));
var inj = injector(ListWrapper.concat([NeedsViewContainer], extraProviders));
expect(inj.get(NeedsViewContainer).viewContainer).toBeAnInstanceOf(ViewContainerRef_);
});
it("should inject TemplateRef", () => {
var templateRef = new TemplateRef_(<any>new SpyElementRef());
var inj = injector(ListWrapper.concat([NeedsTemplateRef], extraBindings), null, false,
var inj = injector(ListWrapper.concat([NeedsTemplateRef], extraProviders), null, false,
new PreBuiltObjects(null, null, null, templateRef));
expect(inj.get(NeedsTemplateRef).templateRef).toEqual(templateRef);
});
it("should throw if there is no TemplateRef", () => {
expect(() => injector(ListWrapper.concat([NeedsTemplateRef], extraBindings)))
expect(() => injector(ListWrapper.concat([NeedsTemplateRef], extraProviders)))
.toThrowError(
`No provider for TemplateRef! (${stringify(NeedsTemplateRef) } -> TemplateRef)`);
});
it('should inject null if there is no TemplateRef when the dependency is optional', () => {
var inj = injector(ListWrapper.concat([OptionallyInjectsTemplateRef], extraBindings));
var inj = injector(ListWrapper.concat([OptionallyInjectsTemplateRef], extraProviders));
var instance = inj.get(OptionallyInjectsTemplateRef);
expect(instance.templateRef).toBeNull();
});
@ -950,7 +944,7 @@ export function main() {
it('should be injectable', () => {
var inj =
injector(ListWrapper.concat([NeedsQuery], extraBindings), null, false, preBuildObjects);
injector(ListWrapper.concat([NeedsQuery], extraProviders), null, false, preBuildObjects);
expect(inj.get(NeedsQuery).query).toBeAnInstanceOf(QueryList);
});
@ -958,7 +952,7 @@ export function main() {
var inj = injector(ListWrapper.concat([
NeedsQuery,
CountingDirective
], extraBindings), null,
], extraProviders), null,
false, preBuildObjects);
addInj(dummyView, inj);
@ -971,7 +965,7 @@ export function main() {
var preBuiltObjects = new PreBuiltObjects(null, dummyView, null, new TemplateRef_(<any>new SpyElementRef()));
var inj = injector(ListWrapper.concat([
NeedsTemplateRefQuery
], extraBindings), null,
], extraProviders), null,
false, preBuiltObjects);
addInj(dummyView, inj);
@ -980,14 +974,14 @@ export function main() {
expect(inj.get(NeedsTemplateRefQuery).query.first).toBe(preBuiltObjects.templateRef);
});
it('should contain the element when no directives are bound to the var binding', () => {
it('should contain the element when no directives are bound to the var provider', () => {
var dirs = [NeedsQueryByVarBindings];
var dirVariableBindings = MapWrapper.createFromStringMap({
"one": null // element
});
var inj = injector(dirs.concat(extraBindings), null,
var inj = injector(dirs.concat(extraProviders), null,
false, preBuildObjects, null, dirVariableBindings);
addInj(dummyView, inj);
@ -996,8 +990,8 @@ export function main() {
expect(inj.get(NeedsQueryByVarBindings).query.first).toBe(preBuildObjects.elementRef);
});
it('should contain directives on the same injector when querying by variable bindings' +
'in the order of var bindings specified in the query', () => {
it('should contain directives on the same injector when querying by variable providers' +
'in the order of var providers specified in the query', () => {
var dirs = [NeedsQueryByVarBindings, NeedsDirective, SimpleDirective];
var dirVariableBindings = MapWrapper.createFromStringMap({
@ -1005,7 +999,7 @@ export function main() {
"two": 1 // 1 is the index of NeedsDirective
});
var inj = injector(dirs.concat(extraBindings), null,
var inj = injector(dirs.concat(extraProviders), null,
false, preBuildObjects, null, dirVariableBindings);
addInj(dummyView, inj);
@ -1019,7 +1013,7 @@ export function main() {
it('should contain directives on the same and a child injector in construction order', () => {
var protoParent = createPei(null, 0, [NeedsQuery, CountingDirective]);
var protoChild =
createPei(protoParent, 1, ListWrapper.concat([CountingDirective], extraBindings));
createPei(protoParent, 1, ListWrapper.concat([CountingDirective], extraProviders));
var parent = protoParent.instantiate(null);
var child = protoChild.instantiate(parent);

View File

@ -46,8 +46,9 @@ import {
import {
Injector,
bind,
provide,
Injectable,
Binding,
Provider,
forwardRef,
OpaqueToken,
Inject,
@ -96,7 +97,7 @@ const ANCHOR_ELEMENT = CONST_EXPR(new OpaqueToken('AnchorElement'));
export function main() {
describe('integration tests', function() {
beforeEachBindings(() => [bind(ANCHOR_ELEMENT).toValue(el('<div></div>'))]);
beforeEachBindings(() => [provide(ANCHOR_ELEMENT, {asValue: el('<div></div>')})]);
describe('react to record changes', function() {
it('should consume text node changes',
@ -1081,7 +1082,7 @@ export function main() {
});
}));
it("should support viewBindings",
it("should support viewProviders",
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
tcb.overrideView(DirectiveProvidingInjectableInView, new ViewMetadata({
template: `
@ -1515,8 +1516,8 @@ export function main() {
describe('logging property updates', () => {
beforeEachBindings(() => [
bind(ChangeDetectorGenConfig)
.toValue(new ChangeDetectorGenConfig(true, true, true, false))
provide(ChangeDetectorGenConfig,
{asValue: new ChangeDetectorGenConfig(true, true, true, false)})
]);
it('should reflect property values as attributes',
@ -1740,7 +1741,7 @@ class DynamicViewport {
var myService = new MyService();
myService.greeting = 'dynamic greet';
var bindings = Injector.resolve([bind(MyService).toValue(myService)]);
var bindings = Injector.resolve([provide(MyService, {asValue: myService})]);
this.done = compiler.compileInHost(ChildCompUsingService)
.then((hostPv) => {vc.createHostView(hostPv, 0, bindings)});
}
@ -1841,7 +1842,7 @@ class MyComp {
throwError() { throw 'boom'; }
}
@Component({selector: 'child-cmp', inputs: ['dirProp'], viewBindings: [MyService]})
@Component({selector: 'child-cmp', inputs: ['dirProp'], viewProviders: [MyService]})
@View({directives: [MyDir], template: '{{ctxProp}}'})
@Injectable()
class ChildComp {
@ -1883,7 +1884,7 @@ class CompWithHost {
constructor(@Host() someComp: SomeDirective) { this.myHost = someComp; }
}
@Component({selector: '[child-cmp2]', viewBindings: [MyService]})
@Component({selector: '[child-cmp2]', viewProviders: [MyService]})
@Injectable()
class ChildComp2 {
ctxProp: string;
@ -2025,7 +2026,7 @@ class PublicApi {
@Directive({
selector: '[public-api]',
bindings: [new Binding(PublicApi, {toAlias: PrivateImpl, deps: []})]
providers: [new Provider(PublicApi, {toAlias: PrivateImpl, deps: []})]
})
@Injectable()
class PrivateImpl extends PublicApi {
@ -2092,8 +2093,9 @@ function createInjectableWithLogging(inj: Injector) {
@Component({
selector: 'component-providing-logging-injectable',
bindings:
[new Binding(InjectableService, {toFactory: createInjectableWithLogging, deps: [Injector]})]
providers: [
new Provider(InjectableService, {toFactory: createInjectableWithLogging, deps: [Injector]})
]
})
@View({template: ''})
@Injectable()
@ -2102,12 +2104,12 @@ class ComponentProvidingLoggingInjectable {
}
@Directive({selector: 'directive-providing-injectable', bindings: [[InjectableService]]})
@Directive({selector: 'directive-providing-injectable', providers: [[InjectableService]]})
@Injectable()
class DirectiveProvidingInjectable {
}
@Component({selector: 'directive-providing-injectable', viewBindings: [[InjectableService]]})
@Component({selector: 'directive-providing-injectable', viewProviders: [[InjectableService]]})
@View({template: ''})
@Injectable()
class DirectiveProvidingInjectableInView {
@ -2115,8 +2117,8 @@ class DirectiveProvidingInjectableInView {
@Component({
selector: 'directive-providing-injectable',
bindings: [new Binding(InjectableService, {toValue: 'host'})],
viewBindings: [new Binding(InjectableService, {toValue: 'view'})]
providers: [new Provider(InjectableService, {toValue: 'host'})],
viewProviders: [new Provider(InjectableService, {toValue: 'view'})]
})
@View({template: ''})
@Injectable()
@ -2168,7 +2170,7 @@ class EventBus {
@Directive({
selector: 'grand-parent-providing-event-bus',
bindings: [new Binding(EventBus, {toValue: new EventBus(null, "grandparent")})]
providers: [new Provider(EventBus, {toValue: new EventBus(null, "grandparent")})]
})
class GrandParentProvidingEventBus {
bus: EventBus;
@ -2182,9 +2184,9 @@ function createParentBus(peb) {
@Component({
selector: 'parent-providing-event-bus',
bindings: [
new Binding(EventBus,
{toFactory: createParentBus, deps: [[EventBus, new SkipSelfMetadata()]]})
providers: [
new Provider(EventBus,
{toFactory: createParentBus, deps: [[EventBus, new SkipSelfMetadata()]]})
]
})
@View({

Some files were not shown because too many files have changed in this diff Show More