parent
7c6130c2c5
commit
1eb0162cde
@ -72,7 +72,7 @@ module.exports = new Package('angular-v2-docs', [jsdocPackage, nunjucksPackage,
|
|||||||
{
|
{
|
||||||
id: 'angular2/test_lib',
|
id: 'angular2/test_lib',
|
||||||
references: ['./angular2.d.ts'],
|
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',
|
Predicate: 'ng.Predicate', ElementRef: 'ng.ElementRef', DebugElement: 'ng.DebugElement',
|
||||||
InjectableReference: 'ng.InjectableReference', ComponentRef: 'ng.ComponentRef' },
|
InjectableReference: 'ng.InjectableReference', ComponentRef: 'ng.ComponentRef' },
|
||||||
modules: {'angular2/test_lib': {namespace: 'ngTestLib', id: 'angular2/test_lib'}}
|
modules: {'angular2/test_lib': {namespace: 'ngTestLib', id: 'angular2/test_lib'}}
|
||||||
|
@ -8,5 +8,5 @@ library angular2;
|
|||||||
export 'package:angular2/core.dart' hide forwardRef, resolveForwardRef, ForwardRefFn;
|
export 'package:angular2/core.dart' hide forwardRef, resolveForwardRef, ForwardRefFn;
|
||||||
export 'package:angular2/profile.dart';
|
export 'package:angular2/profile.dart';
|
||||||
export 'package:angular2/lifecycle_hooks.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';
|
export 'package:angular2/src/core/render/dom/dom_tokens.dart';
|
||||||
|
@ -108,7 +108,7 @@ while (inj) {
|
|||||||
inj = inj.parent;
|
inj = inj.parent;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
throw new NoBindingError(requestedKey);
|
throw new NoProviderError(requestedKey);
|
||||||
```
|
```
|
||||||
|
|
||||||
So in the following example
|
So in the following example
|
||||||
@ -160,7 +160,7 @@ var child = parent.resolveAndCreateChild([
|
|||||||
bind(Engine).toClass(TurboEngine)
|
bind(Engine).toClass(TurboEngine)
|
||||||
]);
|
]);
|
||||||
|
|
||||||
parent.get(Car); // will throw NoBindingError
|
parent.get(Car); // will throw NoProviderError
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
* The http module provides services to perform http requests. To get started, see the {@link Http}
|
* The http module provides services to perform http requests. To get started, see the {@link Http}
|
||||||
* class.
|
* class.
|
||||||
*/
|
*/
|
||||||
import {bind, Binding} from 'angular2/core';
|
import {provide, Provider} from 'angular2/core';
|
||||||
import {Http, Jsonp} from './src/http/http';
|
import {Http, Jsonp} from './src/http/http';
|
||||||
import {XHRBackend, XHRConnection} from './src/http/backends/xhr_backend';
|
import {XHRBackend, XHRConnection} from './src/http/backends/xhr_backend';
|
||||||
import {JSONPBackend, JSONPBackend_, JSONPConnection} from './src/http/backends/jsonp_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.
|
* 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.
|
* or in the root injector when bootstrapping an application.
|
||||||
*
|
*
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/snj7Nv?p=preview))
|
* ### Example ([live demo](http://plnkr.co/edit/snj7Nv?p=preview))
|
||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
* import {bootstrap, Component, NgFor, View} from 'angular2/angular2';
|
* import {bootstrap, Component, NgFor, View} from 'angular2/angular2';
|
||||||
* import {HTTP_BINDINGS, Http} from 'angular2/http';
|
* import {HTTP_PROVIDERS, Http} from 'angular2/http';
|
||||||
*
|
*
|
||||||
* @Component({
|
* @Component({
|
||||||
* selector: 'app',
|
* selector: 'app',
|
||||||
* bindings: [HTTP_BINDINGS]
|
* providers: [HTTP_PROVIDERS]
|
||||||
* })
|
* })
|
||||||
* @View({
|
* @View({
|
||||||
* template: `
|
* template: `
|
||||||
@ -83,11 +83,11 @@ export {URLSearchParams} from './src/http/url_search_params';
|
|||||||
* .catch(err => console.error(err));
|
* .catch(err => console.error(err));
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
* The primary public API included in `HTTP_BINDINGS` is the {@link Http} class.
|
* The primary public API included in `HTTP_PROVIDERS` is the {@link Http} class.
|
||||||
* However, other bindings required by `Http` are included,
|
* However, other providers required by `Http` are included,
|
||||||
* which may be beneficial to override in certain cases.
|
* 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 Http}
|
||||||
* * {@link XHRBackend}
|
* * {@link XHRBackend}
|
||||||
* * `BrowserXHR` - Private factory to create `XMLHttpRequest` instances
|
* * `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,
|
* 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.
|
* such as to add a search string to be appended to all URLs.
|
||||||
* To accomplish this, a new binding for {@link RequestOptions} should
|
* To accomplish this, a new provider for {@link RequestOptions} should
|
||||||
* be added in the same injector as `HTTP_BINDINGS`.
|
* be added in the same injector as `HTTP_PROVIDERS`.
|
||||||
*
|
*
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/aCMEXi?p=preview))
|
* ### Example ([live demo](http://plnkr.co/edit/aCMEXi?p=preview))
|
||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
* import {bind, bootstrap} from 'angular2/angular2';
|
* import {provide, bootstrap} from 'angular2/angular2';
|
||||||
* import {HTTP_BINDINGS, BaseRequestOptions, RequestOptions} from 'angular2/http';
|
* import {HTTP_PROVIDERS, BaseRequestOptions, RequestOptions} from 'angular2/http';
|
||||||
*
|
*
|
||||||
* class MyOptions extends BaseRequestOptions {
|
* class MyOptions extends BaseRequestOptions {
|
||||||
* search: string = 'coreTeam=true';
|
* 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));
|
* .catch(err => console.error(err));
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
* Likewise, to use a mock backend for unit tests, the {@link XHRBackend}
|
* 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))
|
* ### Example ([live demo](http://plnkr.co/edit/7LWALD?p=preview))
|
||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
* import {bind, Injector} from 'angular2/angular2';
|
* import {provide, Injector} from 'angular2/angular2';
|
||||||
* import {HTTP_BINDINGS, Http, Response, XHRBackend, MockBackend} from 'angular2/http';
|
* import {HTTP_PROVIDERS, Http, Response, XHRBackend, MockBackend} from 'angular2/http';
|
||||||
*
|
*
|
||||||
* var people = [{name: 'Jeff'}, {name: 'Tobias'}];
|
* var people = [{name: 'Jeff'}, {name: 'Tobias'}];
|
||||||
*
|
*
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* HTTP_BINDINGS,
|
* HTTP_PROVIDERS,
|
||||||
* MockBackend,
|
* MockBackend,
|
||||||
* bind(XHRBackend).toAlias(MockBackend)
|
* provide(XHRBackend, {asAlias: MockBackend})
|
||||||
* ]);
|
* ]);
|
||||||
* var http = injector.get(Http);
|
* var http = injector.get(Http);
|
||||||
* var backend = injector.get(MockBackend);
|
* 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
|
// TODO(pascal): use factory type annotations once supported in DI
|
||||||
// issue: https://github.com/angular/angular/issues/3183
|
// issue: https://github.com/angular/angular/issues/3183
|
||||||
bind(Http)
|
provide(Http,
|
||||||
.toFactory((xhrBackend, requestOptions) => { return new Http(xhrBackend, requestOptions);},
|
{
|
||||||
[XHRBackend, RequestOptions]),
|
asFactory: (xhrBackend, requestOptions) => new Http(xhrBackend, requestOptions),
|
||||||
|
deps: [XHRBackend, RequestOptions]
|
||||||
|
}),
|
||||||
BrowserXhr,
|
BrowserXhr,
|
||||||
bind(RequestOptions).toClass(BaseRequestOptions),
|
provide(RequestOptions, {asClass: BaseRequestOptions}),
|
||||||
bind(ResponseOptions).toClass(BaseResponseOptions),
|
provide(ResponseOptions, {asClass: BaseResponseOptions}),
|
||||||
XHRBackend
|
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.
|
* or in the root injector when bootstrapping an application.
|
||||||
*
|
*
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/vmeN4F?p=preview))
|
* ### Example ([live demo](http://plnkr.co/edit/vmeN4F?p=preview))
|
||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
* import {Component, NgFor, View} from 'angular2/angular2';
|
* import {Component, NgFor, View} from 'angular2/angular2';
|
||||||
* import {JSONP_BINDINGS, Jsonp} from 'angular2/http';
|
* import {JSONP_PROVIDERS, Jsonp} from 'angular2/http';
|
||||||
*
|
*
|
||||||
* @Component({
|
* @Component({
|
||||||
* selector: 'app',
|
* selector: 'app',
|
||||||
* bindings: [JSONP_BINDINGS]
|
* providers: [JSONP_PROVIDERS]
|
||||||
* })
|
* })
|
||||||
* @View({
|
* @View({
|
||||||
* template: `
|
* template: `
|
||||||
@ -202,11 +208,11 @@ export const HTTP_BINDINGS: any[] = [
|
|||||||
* }
|
* }
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
* The primary public API included in `JSONP_BINDINGS` is the {@link Jsonp} class.
|
* The primary public API included in `JSONP_PROVIDERS` is the {@link Jsonp} class.
|
||||||
* However, other bindings required by `Jsonp` are included,
|
* However, other providers required by `Jsonp` are included,
|
||||||
* which may be beneficial to override in certain cases.
|
* 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 Jsonp}
|
||||||
* * {@link JSONPBackend}
|
* * {@link JSONPBackend}
|
||||||
* * `BrowserJsonp` - Private factory
|
* * `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,
|
* 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.
|
* such as to add a search string to be appended to all URLs.
|
||||||
* To accomplish this, a new binding for {@link RequestOptions} should
|
* To accomplish this, a new provider for {@link RequestOptions} should
|
||||||
* be added in the same injector as `JSONP_BINDINGS`.
|
* be added in the same injector as `JSONP_PROVIDERS`.
|
||||||
*
|
*
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/TFug7x?p=preview))
|
* ### Example ([live demo](http://plnkr.co/edit/TFug7x?p=preview))
|
||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
* import {bind, bootstrap} from 'angular2/angular2';
|
* import {provide, bootstrap} from 'angular2/angular2';
|
||||||
* import {JSONP_BINDINGS, BaseRequestOptions, RequestOptions} from 'angular2/http';
|
* import {JSONP_PROVIDERS, BaseRequestOptions, RequestOptions} from 'angular2/http';
|
||||||
*
|
*
|
||||||
* class MyOptions extends BaseRequestOptions {
|
* class MyOptions extends BaseRequestOptions {
|
||||||
* search: string = 'coreTeam=true';
|
* 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));
|
* .catch(err => console.error(err));
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
* Likewise, to use a mock backend for unit tests, the {@link JSONPBackend}
|
* 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))
|
* ### Example ([live demo](http://plnkr.co/edit/HDqZWL?p=preview))
|
||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
* import {bind, Injector} from 'angular2/angular2';
|
* import {provide, Injector} from 'angular2/angular2';
|
||||||
* import {JSONP_BINDINGS, Jsonp, Response, JSONPBackend, MockBackend} from 'angular2/http';
|
* import {JSONP_PROVIDERS, Jsonp, Response, JSONPBackend, MockBackend} from 'angular2/http';
|
||||||
*
|
*
|
||||||
* var people = [{name: 'Jeff'}, {name: 'Tobias'}];
|
* var people = [{name: 'Jeff'}, {name: 'Tobias'}];
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* JSONP_BINDINGS,
|
* JSONP_PROVIDERS,
|
||||||
* MockBackend,
|
* MockBackend,
|
||||||
* bind(JSONPBackend).toAlias(MockBackend)
|
* provide(JSONPBackend, {asAlias: MockBackend})
|
||||||
* ]);
|
* ]);
|
||||||
* var jsonp = injector.get(Jsonp);
|
* var jsonp = injector.get(Jsonp);
|
||||||
* var backend = injector.get(MockBackend);
|
* 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
|
// TODO(pascal): use factory type annotations once supported in DI
|
||||||
// issue: https://github.com/angular/angular/issues/3183
|
// issue: https://github.com/angular/angular/issues/3183
|
||||||
bind(Jsonp)
|
provide(Jsonp,
|
||||||
.toFactory(
|
{
|
||||||
(jsonpBackend, requestOptions) => { return new Jsonp(jsonpBackend, requestOptions);},
|
asFactory: (jsonpBackend, requestOptions) => new Jsonp(jsonpBackend, requestOptions),
|
||||||
[JSONPBackend, RequestOptions]),
|
deps: [JSONPBackend, RequestOptions]
|
||||||
|
}),
|
||||||
BrowserJsonp,
|
BrowserJsonp,
|
||||||
bind(RequestOptions).toClass(BaseRequestOptions),
|
provide(RequestOptions, {asClass: BaseRequestOptions}),
|
||||||
bind(ResponseOptions).toClass(BaseResponseOptions),
|
provide(ResponseOptions, {asClass: BaseResponseOptions}),
|
||||||
bind(JSONPBackend).toClass(JSONPBackend_)
|
provide(JSONPBackend, {asClass: JSONPBackend_})
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated
|
||||||
|
*/
|
||||||
|
export const JSON_BINDINGS = JSONP_PROVIDERS;
|
@ -28,7 +28,7 @@ import {RouterOutlet} from './src/router/router_outlet';
|
|||||||
import {RouterLink} from './src/router/router_link';
|
import {RouterLink} from './src/router/router_link';
|
||||||
import {RouteRegistry} from './src/router/route_registry';
|
import {RouteRegistry} from './src/router/route_registry';
|
||||||
import {Location} from './src/router/location';
|
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 {CONST_EXPR} from './src/core/facade/lang';
|
||||||
import {ApplicationRef} from './src/core/application_ref';
|
import {ApplicationRef} from './src/core/application_ref';
|
||||||
import {BaseException} from 'angular2/src/core/facade/exceptions';
|
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 {Component, View} from 'angular2/angular2';
|
||||||
* import {
|
* import {
|
||||||
* ROUTER_DIRECTIVES,
|
* ROUTER_DIRECTIVES,
|
||||||
* ROUTER_BINDINGS,
|
* ROUTER_PROVIDERS,
|
||||||
* RouteConfig
|
* RouteConfig
|
||||||
* } from 'angular2/router';
|
* } 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 =
|
export const ROUTER_PRIMARY_COMPONENT: OpaqueToken =
|
||||||
@ -72,7 +72,7 @@ export const ROUTER_PRIMARY_COMPONENT: OpaqueToken =
|
|||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
* import {Component, View} from 'angular2/angular2';
|
* 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({...})
|
* @Component({...})
|
||||||
* @View({directives: [ROUTER_DIRECTIVES]})
|
* @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]);
|
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))
|
* ## 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 {Component, View} from 'angular2/angular2';
|
||||||
* import {
|
* import {
|
||||||
* ROUTER_DIRECTIVES,
|
* ROUTER_DIRECTIVES,
|
||||||
* ROUTER_BINDINGS,
|
* ROUTER_PROVIDERS,
|
||||||
* RouteConfig
|
* RouteConfig
|
||||||
* } from 'angular2/router';
|
* } 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,
|
RouteRegistry,
|
||||||
CONST_EXPR(new Binding(LocationStrategy, {toClass: PathLocationStrategy})),
|
CONST_EXPR(new Provider(LocationStrategy, {toClass: PathLocationStrategy})),
|
||||||
Location,
|
Location,
|
||||||
CONST_EXPR(new Binding(Router,
|
CONST_EXPR(
|
||||||
{
|
new Provider(Router,
|
||||||
toFactory: routerFactory,
|
{
|
||||||
deps: CONST_EXPR([RouteRegistry, Location, ROUTER_PRIMARY_COMPONENT])
|
toFactory: routerFactory,
|
||||||
})),
|
deps: CONST_EXPR([RouteRegistry, Location, ROUTER_PRIMARY_COMPONENT])
|
||||||
CONST_EXPR(new Binding(
|
})),
|
||||||
|
CONST_EXPR(new Provider(
|
||||||
ROUTER_PRIMARY_COMPONENT,
|
ROUTER_PRIMARY_COMPONENT,
|
||||||
{toFactory: routerPrimaryComponentFactory, deps: CONST_EXPR([ApplicationRef])}))
|
{toFactory: routerPrimaryComponentFactory, deps: CONST_EXPR([ApplicationRef])}))
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated
|
||||||
|
*/
|
||||||
|
export const ROUTER_BINDINGS = ROUTER_PROVIDERS;
|
||||||
|
|
||||||
function routerFactory(registry, location, primaryComponent) {
|
function routerFactory(registry, location, primaryComponent) {
|
||||||
return new RootRouter(registry, location, primaryComponent);
|
return new RootRouter(registry, location, primaryComponent);
|
||||||
}
|
}
|
||||||
|
@ -18,11 +18,11 @@ export 'package:angular2/src/core/linker/dynamic_component_loader.dart' show Com
|
|||||||
///
|
///
|
||||||
/// See [commonBootstrap] for detailed documentation.
|
/// See [commonBootstrap] for detailed documentation.
|
||||||
Future<ComponentRef> bootstrap(Type appComponentType,
|
Future<ComponentRef> bootstrap(Type appComponentType,
|
||||||
[List componentInjectableBindings]) {
|
[List componentInjectableProviders]) {
|
||||||
reflector.reflectionCapabilities = new ReflectionCapabilities();
|
reflector.reflectionCapabilities = new ReflectionCapabilities();
|
||||||
var bindings = [compilerBindings()];
|
var providers = [compilerProviders()];
|
||||||
if (componentInjectableBindings != null) {
|
if (componentInjectableProviders != null) {
|
||||||
bindings.add(componentInjectableBindings);
|
providers.add(componentInjectableProviders);
|
||||||
}
|
}
|
||||||
return commonBootstrap(appComponentType, bindings);
|
return commonBootstrap(appComponentType, providers);
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
// Public API for Application
|
// Public API for Application
|
||||||
import {Binding} from './di';
|
import {Provider} from './di';
|
||||||
import {Type, isPresent} from 'angular2/src/core/facade/lang';
|
import {Type, isPresent} from 'angular2/src/core/facade/lang';
|
||||||
import {Promise} from 'angular2/src/core/facade/async';
|
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 {commonBootstrap} from './application_common';
|
||||||
import {ComponentRef} from './linker/dynamic_component_loader';
|
import {ComponentRef} from './linker/dynamic_component_loader';
|
||||||
|
|
||||||
@ -19,9 +19,9 @@ export {
|
|||||||
|
|
||||||
/// See [commonBootstrap] for detailed documentation.
|
/// See [commonBootstrap] for detailed documentation.
|
||||||
export function bootstrap(appComponentType: /*Type*/ any,
|
export function bootstrap(appComponentType: /*Type*/ any,
|
||||||
appBindings: Array<Type | Binding | any[]> = null):
|
appBindings: Array<Type | Provider | any[]> = null):
|
||||||
Promise<ComponentRef> {
|
Promise<ComponentRef> {
|
||||||
var bindings = [compilerBindings()];
|
var bindings = [compilerProviders()];
|
||||||
if (isPresent(appBindings)) {
|
if (isPresent(appBindings)) {
|
||||||
bindings.push(appBindings);
|
bindings.push(appBindings);
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import {FORM_BINDINGS} from 'angular2/src/core/forms';
|
import {FORM_PROVIDERS} from 'angular2/src/core/forms';
|
||||||
import {bind, Binding, Injector, OpaqueToken} from 'angular2/src/core/di';
|
import {provide, Provider, Injector, OpaqueToken} from 'angular2/src/core/di';
|
||||||
import {
|
import {
|
||||||
NumberWrapper,
|
NumberWrapper,
|
||||||
Type,
|
Type,
|
||||||
@ -34,37 +34,36 @@ import {
|
|||||||
SharedStylesHost,
|
SharedStylesHost,
|
||||||
DomSharedStylesHost
|
DomSharedStylesHost
|
||||||
} from 'angular2/src/core/render/dom/shared_styles_host';
|
} 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 {AnimationBuilder} from 'angular2/src/animate/animation_builder';
|
||||||
import {BrowserDetails} from 'angular2/src/animate/browser_details';
|
import {BrowserDetails} from 'angular2/src/animate/browser_details';
|
||||||
import {wtfInit} from './profile/wtf_init';
|
import {wtfInit} from './profile/wtf_init';
|
||||||
import {platformCommon, PlatformRef, applicationCommonBindings} from './application_ref';
|
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.
|
* the UI thread.
|
||||||
*/
|
*/
|
||||||
export function applicationDomBindings(): Array<Type | Binding | any[]> {
|
export function applicationDomBindings(): Array<Type | Provider | any[]> {
|
||||||
if (isBlank(DOM)) {
|
if (isBlank(DOM)) {
|
||||||
throw "Must set a root DOM adapter first.";
|
throw "Must set a root DOM adapter first.";
|
||||||
}
|
}
|
||||||
return [
|
return [
|
||||||
bind(DOCUMENT)
|
provide(DOCUMENT, {asValue: DOM.defaultDoc()}),
|
||||||
.toValue(DOM.defaultDoc()),
|
|
||||||
EventManager,
|
EventManager,
|
||||||
new Binding(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true}),
|
new Provider(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true}),
|
||||||
new Binding(EVENT_MANAGER_PLUGINS, {toClass: KeyEventsPlugin, multi: true}),
|
new Provider(EVENT_MANAGER_PLUGINS, {toClass: KeyEventsPlugin, multi: true}),
|
||||||
new Binding(EVENT_MANAGER_PLUGINS, {toClass: HammerGesturesPlugin, multi: true}),
|
new Provider(EVENT_MANAGER_PLUGINS, {toClass: HammerGesturesPlugin, multi: true}),
|
||||||
bind(DomRenderer).toClass(DomRenderer_),
|
provide(DomRenderer, {asClass: DomRenderer_}),
|
||||||
bind(Renderer).toAlias(DomRenderer),
|
provide(Renderer, {asAlias: DomRenderer}),
|
||||||
DomSharedStylesHost,
|
DomSharedStylesHost,
|
||||||
bind(SharedStylesHost).toAlias(DomSharedStylesHost),
|
provide(SharedStylesHost, {asAlias: DomSharedStylesHost}),
|
||||||
EXCEPTION_BINDING,
|
EXCEPTION_PROVIDER,
|
||||||
bind(XHR).toValue(new XHRImpl()),
|
provide(XHR, {asValue: new XHRImpl()}),
|
||||||
Testability,
|
Testability,
|
||||||
BrowserDetails,
|
BrowserDetails,
|
||||||
AnimationBuilder,
|
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.
|
* 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:
|
* platform exists:
|
||||||
*
|
*
|
||||||
* If no platform exists, a new one will be created with the default {@link platformBindings}.
|
* 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
|
* was created with). This is a convenience feature, allowing for multiple applications
|
||||||
* to be loaded into the same platform without awareness of each other.
|
* 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
|
* 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
|
* 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.
|
* 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
|
* them if a platform did not exist already. If it did exist, however, an error will be
|
||||||
* thrown.
|
* thrown.
|
||||||
*
|
*
|
||||||
@ -101,7 +100,7 @@ export function applicationDomBindings(): Array<Type | Binding | any[]> {
|
|||||||
* DOM access. Web-worker applications should call `platform` from
|
* DOM access. Web-worker applications should call `platform` from
|
||||||
* `src/web_workers/worker/application_common` instead.
|
* `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, () => {
|
return platformCommon(bindings, () => {
|
||||||
BrowserDomAdapter.makeCurrent();
|
BrowserDomAdapter.makeCurrent();
|
||||||
wtfInit();
|
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`.
|
* 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
|
* 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
|
* 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 }}`.
|
* Angular 2 component double-curly `{{ syntax }}`.
|
||||||
*
|
*
|
||||||
* We can use this script code:
|
* 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
|
* 4. It creates a shadow DOM on the selected component's host element and loads the
|
||||||
* template into it.
|
* template into it.
|
||||||
* 5. It instantiates the specified component.
|
* 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.
|
* application.
|
||||||
*
|
*
|
||||||
*
|
*
|
||||||
@ -214,7 +213,7 @@ export function platform(bindings?: Array<Type | Binding | any[]>): PlatformRef
|
|||||||
* # API
|
* # API
|
||||||
* - `appComponentType`: The root component which should act as the application. This is
|
* - `appComponentType`: The root component which should act as the application. This is
|
||||||
* a reference to a `Type` which is annotated with `@Component(...)`.
|
* 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.
|
* app injector to override default injection behavior.
|
||||||
* - `errorReporter`: `function(exception:any, stackTrace:string)` a default error reporter
|
* - `errorReporter`: `function(exception:any, stackTrace:string)` a default error reporter
|
||||||
* for unhandled exceptions.
|
* for unhandled exceptions.
|
||||||
@ -222,7 +221,7 @@ export function platform(bindings?: Array<Type | Binding | any[]>): PlatformRef
|
|||||||
* Returns a `Promise` of {@link ComponentRef}.
|
* Returns a `Promise` of {@link ComponentRef}.
|
||||||
*/
|
*/
|
||||||
export function commonBootstrap(appComponentType: /*Type*/ any,
|
export function commonBootstrap(appComponentType: /*Type*/ any,
|
||||||
appBindings: Array<Type | Binding | any[]> = null):
|
appBindings: Array<Type | Provider | any[]> = null):
|
||||||
Promise<ComponentRef> {
|
Promise<ComponentRef> {
|
||||||
var p = platform();
|
var p = platform();
|
||||||
var bindings = [applicationCommonBindings(), applicationDomBindings()];
|
var bindings = [applicationCommonBindings(), applicationDomBindings()];
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
import {NgZone} from 'angular2/src/core/zone/ng_zone';
|
import {NgZone} from 'angular2/src/core/zone/ng_zone';
|
||||||
import {Type, isBlank, isPresent, assertionsEnabled} from 'angular2/src/core/facade/lang';
|
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 {
|
import {
|
||||||
APP_COMPONENT_REF_PROMISE,
|
APP_COMPONENT_REF_PROMISE,
|
||||||
APP_COMPONENT,
|
APP_COMPONENT,
|
||||||
APP_ID_RANDOM_BINDING
|
APP_ID_RANDOM_PROVIDER
|
||||||
} from './application_tokens';
|
} from './application_tokens';
|
||||||
import {Promise, PromiseWrapper, PromiseCompleter} from 'angular2/src/core/facade/async';
|
import {Promise, PromiseWrapper, PromiseCompleter} from 'angular2/src/core/facade/async';
|
||||||
import {ListWrapper} from 'angular2/src/core/facade/collection';
|
import {ListWrapper} from 'angular2/src/core/facade/collection';
|
||||||
@ -44,67 +44,71 @@ import {AppViewManager_} from "./linker/view_manager";
|
|||||||
import {Compiler_} from "./linker/compiler";
|
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.
|
* running on the page.
|
||||||
*/
|
*/
|
||||||
export function platformBindings(): Array<Type | Binding | any[]> {
|
export function platformBindings(): Array<Type | Provider | any[]> {
|
||||||
return [bind(Reflector).toValue(reflector), TestabilityRegistry];
|
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 [
|
return [
|
||||||
bind(APP_COMPONENT)
|
provide(APP_COMPONENT, {asValue: appComponentType}),
|
||||||
.toValue(appComponentType),
|
provide(APP_COMPONENT_REF_PROMISE,
|
||||||
bind(APP_COMPONENT_REF_PROMISE)
|
{
|
||||||
.toFactory(
|
asFactory: (dynamicComponentLoader, injector: Injector) => {
|
||||||
(dynamicComponentLoader, injector: Injector) => {
|
// TODO(rado): investigate whether to support bindings on root component.
|
||||||
// TODO(rado): investigate whether to support bindings on root component.
|
return dynamicComponentLoader.loadAsRoot(appComponentType, null, injector)
|
||||||
return dynamicComponentLoader.loadAsRoot(appComponentType, null, injector)
|
.then((componentRef) => {
|
||||||
.then((componentRef) => {
|
if (isPresent(componentRef.location.nativeElement)) {
|
||||||
if (isPresent(componentRef.location.nativeElement)) {
|
injector.get(TestabilityRegistry)
|
||||||
injector.get(TestabilityRegistry)
|
.registerApplication(componentRef.location.nativeElement,
|
||||||
.registerApplication(componentRef.location.nativeElement,
|
injector.get(Testability));
|
||||||
injector.get(Testability));
|
}
|
||||||
}
|
return componentRef;
|
||||||
return componentRef;
|
});
|
||||||
});
|
},
|
||||||
},
|
deps: [DynamicComponentLoader, Injector]
|
||||||
[DynamicComponentLoader, Injector]),
|
}),
|
||||||
|
provide(appComponentType,
|
||||||
bind(appComponentType)
|
{
|
||||||
.toFactory((p: Promise<any>) => p.then(ref => ref.instance), [APP_COMPONENT_REF_PROMISE]),
|
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.
|
* 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 [
|
return [
|
||||||
bind(Compiler)
|
provide(Compiler, {asClass: Compiler_}),
|
||||||
.toClass(Compiler_),
|
APP_ID_RANDOM_PROVIDER,
|
||||||
APP_ID_RANDOM_BINDING,
|
|
||||||
AppViewPool,
|
AppViewPool,
|
||||||
bind(APP_VIEW_POOL_CAPACITY).toValue(10000),
|
provide(APP_VIEW_POOL_CAPACITY, {asValue: 10000}),
|
||||||
bind(AppViewManager).toClass(AppViewManager_),
|
provide(AppViewManager, {asClass: AppViewManager_}),
|
||||||
AppViewManagerUtils,
|
AppViewManagerUtils,
|
||||||
AppViewListener,
|
AppViewListener,
|
||||||
ProtoViewFactory,
|
ProtoViewFactory,
|
||||||
ViewResolver,
|
ViewResolver,
|
||||||
DEFAULT_PIPES,
|
DEFAULT_PIPES,
|
||||||
bind(IterableDiffers).toValue(defaultIterableDiffers),
|
provide(IterableDiffers, {asValue: defaultIterableDiffers}),
|
||||||
bind(KeyValueDiffers).toValue(defaultKeyValueDiffers),
|
provide(KeyValueDiffers, {asValue: defaultKeyValueDiffers}),
|
||||||
DirectiveResolver,
|
DirectiveResolver,
|
||||||
PipeResolver,
|
PipeResolver,
|
||||||
bind(DynamicComponentLoader).toClass(DynamicComponentLoader_),
|
provide(DynamicComponentLoader, {asClass: DynamicComponentLoader_}),
|
||||||
bind(LifeCycle).toFactory((exceptionHandler) => new LifeCycle_(null, assertionsEnabled()),
|
provide(LifeCycle,
|
||||||
[ExceptionHandler]),
|
{
|
||||||
|
asFactory: (exceptionHandler) => new LifeCycle_(null, assertionsEnabled()),
|
||||||
|
deps: [ExceptionHandler]
|
||||||
|
})
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -117,7 +121,7 @@ export function createNgZone(): NgZone {
|
|||||||
|
|
||||||
var _platform: PlatformRef;
|
var _platform: PlatformRef;
|
||||||
|
|
||||||
export function platformCommon(bindings?: Array<Type | Binding | any[]>, initializer?: () => void):
|
export function platformCommon(bindings?: Array<Type | Provider | any[]>, initializer?: () => void):
|
||||||
PlatformRef {
|
PlatformRef {
|
||||||
if (isPresent(_platform)) {
|
if (isPresent(_platform)) {
|
||||||
if (isBlank(bindings)) {
|
if (isBlank(bindings)) {
|
||||||
@ -148,7 +152,7 @@ export function platformCommon(bindings?: Array<Type | Binding | any[]>, initial
|
|||||||
export abstract class PlatformRef {
|
export abstract class PlatformRef {
|
||||||
/**
|
/**
|
||||||
* Retrieve the platform {@link Injector}, which is the parent injector for
|
* 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(); };
|
get injector(): Injector { return unimplemented(); };
|
||||||
|
|
||||||
@ -163,10 +167,10 @@ export abstract class PlatformRef {
|
|||||||
*
|
*
|
||||||
* # Application Bindings
|
* # Application Bindings
|
||||||
*
|
*
|
||||||
* Angular applications require numerous bindings to be properly instantiated.
|
* Angular applications require numerous providers to be properly instantiated.
|
||||||
* When using `application()` to create a new app on the page, these bindings
|
* When using `application()` to create a new app on the page, these providers
|
||||||
* must be provided. Fortunately, there are helper functions to configure
|
* 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
|
* # Example
|
||||||
* ```
|
* ```
|
||||||
@ -180,21 +184,21 @@ export abstract class PlatformRef {
|
|||||||
*
|
*
|
||||||
* See the {@link bootstrap} documentation for more details.
|
* 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
|
* are only available asynchronously. One such use case is to initialize an
|
||||||
* application running in a web worker.
|
* application running in a web worker.
|
||||||
*
|
*
|
||||||
* # Usage
|
* # Usage
|
||||||
*
|
*
|
||||||
* `bindingFn` is a function that will be called in the new application's zone.
|
* `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
|
* new application. Once this promise resolves, the application will be
|
||||||
* constructed in the same manner as a normal `application()`.
|
* 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>;
|
Promise<ApplicationRef>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -211,33 +215,33 @@ export class PlatformRef_ extends PlatformRef {
|
|||||||
|
|
||||||
get injector(): Injector { return this._injector; }
|
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);
|
var app = this._initApp(createNgZone(), bindings);
|
||||||
return app;
|
return app;
|
||||||
}
|
}
|
||||||
|
|
||||||
asyncApplication(bindingFn: (zone: NgZone) =>
|
asyncApplication(bindingFn: (zone: NgZone) =>
|
||||||
Promise<Array<Type | Binding | any[]>>): Promise<ApplicationRef> {
|
Promise<Array<Type | Provider | any[]>>): Promise<ApplicationRef> {
|
||||||
var zone = createNgZone();
|
var zone = createNgZone();
|
||||||
var completer = PromiseWrapper.completer();
|
var completer = PromiseWrapper.completer();
|
||||||
zone.run(() => {
|
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));
|
completer.resolve(this._initApp(zone, bindings));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
return completer.promise;
|
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 injector: Injector;
|
||||||
var app: ApplicationRef;
|
var app: ApplicationRef;
|
||||||
zone.run(() => {
|
zone.run(() => {
|
||||||
bindings.push(bind(NgZone).toValue(zone));
|
providers.push(provide(NgZone, {asValue: zone}));
|
||||||
bindings.push(bind(ApplicationRef).toFactory((): ApplicationRef => app, []));
|
providers.push(provide(ApplicationRef, {asFactory: (): ApplicationRef => app, deps: []}));
|
||||||
|
|
||||||
var exceptionHandler;
|
var exceptionHandler;
|
||||||
try {
|
try {
|
||||||
injector = this.injector.resolveAndCreateChild(bindings);
|
injector = this.injector.resolveAndCreateChild(providers);
|
||||||
exceptionHandler = injector.get(ExceptionHandler);
|
exceptionHandler = injector.get(ExceptionHandler);
|
||||||
zone.overrideOnErrorHandler((e, s) => exceptionHandler.call(e, s));
|
zone.overrideOnErrorHandler((e, s) => exceptionHandler.call(e, s));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@ -285,18 +289,18 @@ export abstract class ApplicationRef {
|
|||||||
*
|
*
|
||||||
* # Optional Bindings
|
* # Optional Bindings
|
||||||
*
|
*
|
||||||
* Bindings for the given component can optionally be overridden via the `bindings`
|
* Bindings for the given component can optionally be overridden via the `providers`
|
||||||
* parameter. These bindings will only apply for the root component being added and any
|
* parameter. These providers will only apply for the root component being added and any
|
||||||
* child components under it.
|
* child components under it.
|
||||||
*
|
*
|
||||||
* # Example
|
* # Example
|
||||||
* ```
|
* ```
|
||||||
* var app = platform.application([applicationCommonBindings(), applicationDomBindings()];
|
* var app = platform.application([applicationCommonBindings(), applicationDomBindings()];
|
||||||
* app.bootstrap(FirstRootComponent);
|
* 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>;
|
Promise<ComponentRef>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -333,17 +337,18 @@ export class ApplicationRef_ extends ApplicationRef {
|
|||||||
this._bootstrapListeners.push(listener);
|
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();
|
var completer = PromiseWrapper.completer();
|
||||||
this._zone.run(() => {
|
this._zone.run(() => {
|
||||||
var componentBindings = _componentBindings(componentType);
|
var componentProviders = _componentProviders(componentType);
|
||||||
if (isPresent(bindings)) {
|
if (isPresent(providers)) {
|
||||||
componentBindings.push(bindings);
|
componentProviders.push(providers);
|
||||||
}
|
}
|
||||||
var exceptionHandler = this._injector.get(ExceptionHandler);
|
var exceptionHandler = this._injector.get(ExceptionHandler);
|
||||||
this._rootComponentTypes.push(componentType);
|
this._rootComponentTypes.push(componentType);
|
||||||
try {
|
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 compRefToken: Promise<ComponentRef> = injector.get(APP_COMPONENT_REF_PROMISE);
|
||||||
var tick = (componentRef) => {
|
var tick = (componentRef) => {
|
||||||
var appChangeDetector = internalView(componentRef.hostView).changeDetector;
|
var appChangeDetector = internalView(componentRef.hostView).changeDetector;
|
||||||
|
@ -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';
|
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.
|
* {@link ViewEncapsulation#Emulated} is being used.
|
||||||
*
|
*
|
||||||
* If you need to avoid randomly generated value to be used as an application id, you can provide
|
* 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.
|
* using this token.
|
||||||
*/
|
*/
|
||||||
export const APP_ID: OpaqueToken = CONST_EXPR(new OpaqueToken('AppId'));
|
export const APP_ID: OpaqueToken = CONST_EXPR(new OpaqueToken('AppId'));
|
||||||
|
|
||||||
function _appIdRandomBindingFactory() {
|
function _appIdRandomProviderFactory() {
|
||||||
return `${_randomChar()}${_randomChar()}${_randomChar()}`;
|
return `${_randomChar()}${_randomChar()}${_randomChar()}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Bindings that will generate a random APP_ID_TOKEN.
|
* Bindings that will generate a random APP_ID_TOKEN.
|
||||||
*/
|
*/
|
||||||
export const APP_ID_RANDOM_BINDING: Binding =
|
export const APP_ID_RANDOM_PROVIDER: Provider =
|
||||||
CONST_EXPR(new Binding(APP_ID, {toFactory: _appIdRandomBindingFactory, deps: []}));
|
CONST_EXPR(new Provider(APP_ID, {toFactory: _appIdRandomProviderFactory, deps: []}));
|
||||||
|
|
||||||
function _randomChar(): string {
|
function _randomChar(): string {
|
||||||
return StringWrapper.fromCharCode(97 + Math.floor(Math.random() * 25));
|
return StringWrapper.fromCharCode(97 + Math.floor(Math.random() * 25));
|
||||||
|
@ -85,7 +85,7 @@ export abstract class ChangeDetectorRef {
|
|||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* @Component({
|
* @Component({
|
||||||
* selector: 'app', bindings: [DataProvider]
|
* selector: 'app', providers: [DataProvider]
|
||||||
* })
|
* })
|
||||||
* @View({
|
* @View({
|
||||||
* template: `
|
* template: `
|
||||||
@ -166,7 +166,7 @@ export abstract class ChangeDetectorRef {
|
|||||||
*
|
*
|
||||||
* @Component({
|
* @Component({
|
||||||
* selector: 'app',
|
* selector: 'app',
|
||||||
* bindings: [DataProvider]
|
* providers: [DataProvider]
|
||||||
* })
|
* })
|
||||||
* @View({
|
* @View({
|
||||||
* template: `
|
* template: `
|
||||||
|
@ -2,7 +2,7 @@ import {isBlank, isPresent, CONST} from 'angular2/src/core/facade/lang';
|
|||||||
import {BaseException} from 'angular2/src/core/facade/exceptions';
|
import {BaseException} from 'angular2/src/core/facade/exceptions';
|
||||||
import {ListWrapper} from 'angular2/src/core/facade/collection';
|
import {ListWrapper} from 'angular2/src/core/facade/collection';
|
||||||
import {ChangeDetectorRef} from '../change_detector_ref';
|
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 {
|
export interface IterableDiffer {
|
||||||
diff(object: Object): any;
|
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
|
* inherited {@link IterableDiffers} instance with the provided factories and return a new
|
||||||
* {@link IterableDiffers} instance.
|
* {@link IterableDiffers} instance.
|
||||||
*
|
*
|
||||||
@ -48,14 +48,14 @@ export class IterableDiffers {
|
|||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
* @Component({
|
* @Component({
|
||||||
* viewBindings: [
|
* viewProviders: [
|
||||||
* IterableDiffers.extend([new ImmutableListDiffer()])
|
* IterableDiffers.extend([new ImmutableListDiffer()])
|
||||||
* ]
|
* ]
|
||||||
* })
|
* })
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
static extend(factories: IterableDifferFactory[]): Binding {
|
static extend(factories: IterableDifferFactory[]): Provider {
|
||||||
return new Binding(IterableDiffers, {
|
return new Provider(IterableDiffers, {
|
||||||
toFactory: (parent: IterableDiffers) => {
|
toFactory: (parent: IterableDiffers) => {
|
||||||
if (isBlank(parent)) {
|
if (isBlank(parent)) {
|
||||||
// Typically would occur when calling IterableDiffers.extend inside of dependencies passed
|
// Typically would occur when calling IterableDiffers.extend inside of dependencies passed
|
||||||
|
@ -2,7 +2,7 @@ import {isBlank, isPresent, CONST} from 'angular2/src/core/facade/lang';
|
|||||||
import {BaseException} from 'angular2/src/core/facade/exceptions';
|
import {BaseException} from 'angular2/src/core/facade/exceptions';
|
||||||
import {ListWrapper} from 'angular2/src/core/facade/collection';
|
import {ListWrapper} from 'angular2/src/core/facade/collection';
|
||||||
import {ChangeDetectorRef} from '../change_detector_ref';
|
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 {
|
export interface KeyValueDiffer {
|
||||||
diff(object: Object);
|
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
|
* inherited {@link KeyValueDiffers} instance with the provided factories and return a new
|
||||||
* {@link KeyValueDiffers} instance.
|
* {@link KeyValueDiffers} instance.
|
||||||
*
|
*
|
||||||
@ -48,14 +48,14 @@ export class KeyValueDiffers {
|
|||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
* @Component({
|
* @Component({
|
||||||
* viewBindings: [
|
* viewProviders: [
|
||||||
* KeyValueDiffers.extend([new ImmutableMapDiffer()])
|
* KeyValueDiffers.extend([new ImmutableMapDiffer()])
|
||||||
* ]
|
* ]
|
||||||
* })
|
* })
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
static extend(factories: KeyValueDifferFactory[]): Binding {
|
static extend(factories: KeyValueDifferFactory[]): Provider {
|
||||||
return new Binding(KeyValueDiffers, {
|
return new Provider(KeyValueDiffers, {
|
||||||
toFactory: (parent: KeyValueDiffers) => {
|
toFactory: (parent: KeyValueDiffers) => {
|
||||||
if (isBlank(parent)) {
|
if (isBlank(parent)) {
|
||||||
// Typically would occur when calling KeyValueDiffers.extend inside of dependencies passed
|
// Typically would occur when calling KeyValueDiffers.extend inside of dependencies passed
|
||||||
|
@ -8,7 +8,7 @@ export {
|
|||||||
export {SourceModule, SourceWithImports} from './source_module';
|
export {SourceModule, SourceWithImports} from './source_module';
|
||||||
|
|
||||||
import {assertionsEnabled, Type} from 'angular2/src/core/facade/lang';
|
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 {TemplateParser} from 'angular2/src/core/compiler/template_parser';
|
||||||
import {HtmlParser} from 'angular2/src/core/compiler/html_parser';
|
import {HtmlParser} from 'angular2/src/core/compiler/html_parser';
|
||||||
import {TemplateNormalizer} from 'angular2/src/core/compiler/template_normalizer';
|
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 {AnchorBasedAppRootUrl} from 'angular2/src/core/compiler/anchor_based_app_root_url';
|
||||||
import {Parser, Lexer} from 'angular2/src/core/change_detection/change_detection';
|
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 [
|
return [
|
||||||
Lexer,
|
Lexer,
|
||||||
Parser,
|
Parser,
|
||||||
@ -40,16 +40,18 @@ export function compilerBindings(): Array<Type | Binding | any[]> {
|
|||||||
StyleCompiler,
|
StyleCompiler,
|
||||||
CommandCompiler,
|
CommandCompiler,
|
||||||
ChangeDetectionCompiler,
|
ChangeDetectionCompiler,
|
||||||
bind(ChangeDetectorGenConfig)
|
provide(ChangeDetectorGenConfig,
|
||||||
.toValue(
|
{
|
||||||
new ChangeDetectorGenConfig(assertionsEnabled(), assertionsEnabled(), false, true)),
|
asValue:
|
||||||
|
new ChangeDetectorGenConfig(assertionsEnabled(), assertionsEnabled(), false, true)
|
||||||
|
}),
|
||||||
TemplateCompiler,
|
TemplateCompiler,
|
||||||
bind(RuntimeCompiler).toClass(RuntimeCompiler_),
|
provide(RuntimeCompiler, {asClass: RuntimeCompiler_}),
|
||||||
bind(Compiler).toAlias(RuntimeCompiler),
|
provide(Compiler, {asAlias: RuntimeCompiler}),
|
||||||
DomElementSchemaRegistry,
|
DomElementSchemaRegistry,
|
||||||
bind(ElementSchemaRegistry).toAlias(DomElementSchemaRegistry),
|
provide(ElementSchemaRegistry, {asAlias: DomElementSchemaRegistry}),
|
||||||
AnchorBasedAppRootUrl,
|
AnchorBasedAppRootUrl,
|
||||||
bind(AppRootUrl).toAlias(AnchorBasedAppRootUrl),
|
provide(AppRootUrl, {asAlias: AnchorBasedAppRootUrl}),
|
||||||
UrlResolver
|
UrlResolver
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
@ -1,2 +1,6 @@
|
|||||||
export {DebugElement, asNativeElements, By, Scope, inspectElement} from './debug/debug_element';
|
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';
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import {CONST_EXPR, isPresent, NumberWrapper, StringWrapper} from 'angular2/src/core/facade/lang';
|
import {CONST_EXPR, isPresent, NumberWrapper, StringWrapper} from 'angular2/src/core/facade/lang';
|
||||||
import {MapWrapper, Map, ListWrapper} from 'angular2/src/core/facade/collection';
|
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 {AppViewListener} from 'angular2/src/core/linker/view_listener';
|
||||||
import {AppView} from 'angular2/src/core/linker/view';
|
import {AppView} from 'angular2/src/core/linker/view';
|
||||||
import {DOM} from 'angular2/src/core/dom/dom_adapter';
|
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,
|
DebugElementViewListener,
|
||||||
CONST_EXPR(new Binding(AppViewListener, {toAlias: DebugElementViewListener})),
|
CONST_EXPR(new Provider(AppViewListener, {toAlias: DebugElementViewListener})),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
export const ELEMENT_PROBE_BINDINGS = ELEMENT_PROBE_PROVIDERS;
|
@ -21,19 +21,23 @@ export {forwardRef, resolveForwardRef, ForwardRefFn} from './di/forward_ref';
|
|||||||
export {Injector} from './di/injector';
|
export {Injector} from './di/injector';
|
||||||
export {
|
export {
|
||||||
Binding,
|
Binding,
|
||||||
BindingBuilder,
|
ProviderBuilder,
|
||||||
ResolvedBinding,
|
ResolvedBinding,
|
||||||
ResolvedFactory,
|
ResolvedFactory,
|
||||||
Dependency,
|
Dependency,
|
||||||
bind
|
bind,
|
||||||
} from './di/binding';
|
|
||||||
|
Provider,
|
||||||
|
ResolvedProvider,
|
||||||
|
provide
|
||||||
|
} from './di/provider';
|
||||||
export {Key, TypeLiteral} from './di/key';
|
export {Key, TypeLiteral} from './di/key';
|
||||||
export {
|
export {
|
||||||
NoBindingError,
|
NoProviderError,
|
||||||
AbstractBindingError,
|
AbstractProviderError,
|
||||||
CyclicDependencyError,
|
CyclicDependencyError,
|
||||||
InstantiationError,
|
InstantiationError,
|
||||||
InvalidBindingError,
|
InvalidProviderError,
|
||||||
NoAnnotationError,
|
NoAnnotationError,
|
||||||
OutOfBoundsError
|
OutOfBoundsError
|
||||||
} from './di/exceptions';
|
} from './di/exceptions';
|
||||||
|
@ -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 */
|
/** @internal */
|
||||||
message: string;
|
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
|
* 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))
|
* ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview))
|
||||||
*
|
*
|
||||||
@ -75,7 +75,7 @@ export class AbstractBindingError extends BaseException {
|
|||||||
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
|
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
export class NoBindingError extends AbstractBindingError {
|
export class NoProviderError extends AbstractProviderError {
|
||||||
constructor(injector: Injector, key: Key) {
|
constructor(injector: Injector, key: Key) {
|
||||||
super(injector, key, function(keys: any[]) {
|
super(injector, key, function(keys: any[]) {
|
||||||
var first = stringify(ListWrapper.first(keys).token);
|
var first = stringify(ListWrapper.first(keys).token);
|
||||||
@ -91,8 +91,8 @@ export class NoBindingError extends AbstractBindingError {
|
|||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* bind("one").toFactory((two) => "two", [[new Inject("two")]]),
|
* provide("one", {asFactory: (two) => "two", deps: [[new Inject("two")]]}),
|
||||||
* bind("two").toFactory((one) => "one", [[new Inject("one")]])
|
* provide("two", {asFactory: (one) => "one", deps: [[new Inject("one")]]})
|
||||||
* ]);
|
* ]);
|
||||||
*
|
*
|
||||||
* expect(() => injector.get("one")).toThrowError();
|
* 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.
|
* 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) {
|
constructor(injector: Injector, key: Key) {
|
||||||
super(injector, key, function(keys: any[]) {
|
super(injector, key, function(keys: any[]) {
|
||||||
return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`;
|
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.
|
* creation.
|
||||||
*
|
*
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview))
|
* ### 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();
|
* expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError();
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
export class InvalidBindingError extends BaseException {
|
export class InvalidProviderError extends BaseException {
|
||||||
constructor(binding) {
|
constructor(provider) {
|
||||||
super("Invalid binding - only instances of Binding and Type are allowed, got: " +
|
super("Invalid provider - only instances of Provider and Type are allowed, got: " +
|
||||||
binding.toString());
|
provider.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -246,20 +246,20 @@ export class OutOfBoundsError extends BaseException {
|
|||||||
|
|
||||||
// TODO: add a working example after alpha38 is released
|
// 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
|
* ### Example
|
||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* expect(() => Injector.resolveAndCreate([
|
* expect(() => Injector.resolveAndCreate([
|
||||||
* new Binding("Strings", {toValue: "string1", multi: true}),
|
* new Provider("Strings", {toValue: "string1", multi: true}),
|
||||||
* new Binding("Strings", {toValue: "string2", multi: false})
|
* new Provider("Strings", {toValue: "string2", multi: false})
|
||||||
* ])).toThrowError();
|
* ])).toThrowError();
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
export class MixingMultiBindingsWithRegularBindings extends BaseException {
|
export class MixingMultiProvidersWithRegularProvidersError extends BaseException {
|
||||||
constructor(binding1, binding2) {
|
constructor(provider1, provider2) {
|
||||||
super("Cannot mix multi bindings and regular bindings, got: " + binding1.toString() + " " +
|
super("Cannot mix multi providers and regular providers, got: " + provider1.toString() + " " +
|
||||||
binding2.toString());
|
provider2.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,21 +1,20 @@
|
|||||||
import {Map, MapWrapper, ListWrapper} from 'angular2/src/core/facade/collection';
|
import {Map, MapWrapper, ListWrapper} from 'angular2/src/core/facade/collection';
|
||||||
import {
|
import {
|
||||||
ResolvedBinding,
|
ResolvedProvider,
|
||||||
Binding,
|
Provider,
|
||||||
Dependency,
|
Dependency,
|
||||||
BindingBuilder,
|
ProviderBuilder,
|
||||||
ResolvedFactory,
|
ResolvedFactory,
|
||||||
bind,
|
provide,
|
||||||
resolveBindings
|
resolveProviders
|
||||||
} from './binding';
|
} from './provider';
|
||||||
import {
|
import {
|
||||||
AbstractBindingError,
|
AbstractProviderError,
|
||||||
NoBindingError,
|
NoProviderError,
|
||||||
CyclicDependencyError,
|
CyclicDependencyError,
|
||||||
InstantiationError,
|
InstantiationError,
|
||||||
InvalidBindingError,
|
InvalidProviderError,
|
||||||
OutOfBoundsError,
|
OutOfBoundsError
|
||||||
MixingMultiBindingsWithRegularBindings
|
|
||||||
} from './exceptions';
|
} from './exceptions';
|
||||||
import {FunctionWrapper, Type, isPresent, isBlank, CONST_EXPR} from 'angular2/src/core/facade/lang';
|
import {FunctionWrapper, Type, isPresent, isBlank, CONST_EXPR} from 'angular2/src/core/facade/lang';
|
||||||
import {Key} from './key';
|
import {Key} from './key';
|
||||||
@ -28,19 +27,19 @@ const _MAX_CONSTRUCTION_COUNTER = 10;
|
|||||||
export const UNDEFINED: Object = CONST_EXPR(new Object());
|
export const UNDEFINED: Object = CONST_EXPR(new Object());
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Visibility of a {@link Binding}.
|
* Visibility of a {@link Provider}.
|
||||||
*/
|
*/
|
||||||
export enum Visibility {
|
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,
|
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,
|
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
|
PublicAndPrivate
|
||||||
}
|
}
|
||||||
@ -52,21 +51,21 @@ function canSee(src: Visibility, dst: Visibility): boolean {
|
|||||||
|
|
||||||
|
|
||||||
export interface ProtoInjectorStrategy {
|
export interface ProtoInjectorStrategy {
|
||||||
getBindingAtIndex(index: number): ResolvedBinding;
|
getProviderAtIndex(index: number): ResolvedProvider;
|
||||||
createInjectorStrategy(inj: Injector): InjectorStrategy;
|
createInjectorStrategy(inj: Injector): InjectorStrategy;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class ProtoInjectorInlineStrategy implements ProtoInjectorStrategy {
|
export class ProtoInjectorInlineStrategy implements ProtoInjectorStrategy {
|
||||||
binding0: ResolvedBinding = null;
|
provider0: ResolvedProvider = null;
|
||||||
binding1: ResolvedBinding = null;
|
provider1: ResolvedProvider = null;
|
||||||
binding2: ResolvedBinding = null;
|
provider2: ResolvedProvider = null;
|
||||||
binding3: ResolvedBinding = null;
|
provider3: ResolvedProvider = null;
|
||||||
binding4: ResolvedBinding = null;
|
provider4: ResolvedProvider = null;
|
||||||
binding5: ResolvedBinding = null;
|
provider5: ResolvedProvider = null;
|
||||||
binding6: ResolvedBinding = null;
|
provider6: ResolvedProvider = null;
|
||||||
binding7: ResolvedBinding = null;
|
provider7: ResolvedProvider = null;
|
||||||
binding8: ResolvedBinding = null;
|
provider8: ResolvedProvider = null;
|
||||||
binding9: ResolvedBinding = null;
|
provider9: ResolvedProvider = null;
|
||||||
|
|
||||||
keyId0: number = null;
|
keyId0: number = null;
|
||||||
keyId1: number = null;
|
keyId1: number = null;
|
||||||
@ -90,72 +89,72 @@ export class ProtoInjectorInlineStrategy implements ProtoInjectorStrategy {
|
|||||||
visibility8: Visibility = null;
|
visibility8: Visibility = null;
|
||||||
visibility9: Visibility = null;
|
visibility9: Visibility = null;
|
||||||
|
|
||||||
constructor(protoEI: ProtoInjector, bwv: BindingWithVisibility[]) {
|
constructor(protoEI: ProtoInjector, bwv: ProviderWithVisibility[]) {
|
||||||
var length = bwv.length;
|
var length = bwv.length;
|
||||||
|
|
||||||
if (length > 0) {
|
if (length > 0) {
|
||||||
this.binding0 = bwv[0].binding;
|
this.provider0 = bwv[0].provider;
|
||||||
this.keyId0 = bwv[0].getKeyId();
|
this.keyId0 = bwv[0].getKeyId();
|
||||||
this.visibility0 = bwv[0].visibility;
|
this.visibility0 = bwv[0].visibility;
|
||||||
}
|
}
|
||||||
if (length > 1) {
|
if (length > 1) {
|
||||||
this.binding1 = bwv[1].binding;
|
this.provider1 = bwv[1].provider;
|
||||||
this.keyId1 = bwv[1].getKeyId();
|
this.keyId1 = bwv[1].getKeyId();
|
||||||
this.visibility1 = bwv[1].visibility;
|
this.visibility1 = bwv[1].visibility;
|
||||||
}
|
}
|
||||||
if (length > 2) {
|
if (length > 2) {
|
||||||
this.binding2 = bwv[2].binding;
|
this.provider2 = bwv[2].provider;
|
||||||
this.keyId2 = bwv[2].getKeyId();
|
this.keyId2 = bwv[2].getKeyId();
|
||||||
this.visibility2 = bwv[2].visibility;
|
this.visibility2 = bwv[2].visibility;
|
||||||
}
|
}
|
||||||
if (length > 3) {
|
if (length > 3) {
|
||||||
this.binding3 = bwv[3].binding;
|
this.provider3 = bwv[3].provider;
|
||||||
this.keyId3 = bwv[3].getKeyId();
|
this.keyId3 = bwv[3].getKeyId();
|
||||||
this.visibility3 = bwv[3].visibility;
|
this.visibility3 = bwv[3].visibility;
|
||||||
}
|
}
|
||||||
if (length > 4) {
|
if (length > 4) {
|
||||||
this.binding4 = bwv[4].binding;
|
this.provider4 = bwv[4].provider;
|
||||||
this.keyId4 = bwv[4].getKeyId();
|
this.keyId4 = bwv[4].getKeyId();
|
||||||
this.visibility4 = bwv[4].visibility;
|
this.visibility4 = bwv[4].visibility;
|
||||||
}
|
}
|
||||||
if (length > 5) {
|
if (length > 5) {
|
||||||
this.binding5 = bwv[5].binding;
|
this.provider5 = bwv[5].provider;
|
||||||
this.keyId5 = bwv[5].getKeyId();
|
this.keyId5 = bwv[5].getKeyId();
|
||||||
this.visibility5 = bwv[5].visibility;
|
this.visibility5 = bwv[5].visibility;
|
||||||
}
|
}
|
||||||
if (length > 6) {
|
if (length > 6) {
|
||||||
this.binding6 = bwv[6].binding;
|
this.provider6 = bwv[6].provider;
|
||||||
this.keyId6 = bwv[6].getKeyId();
|
this.keyId6 = bwv[6].getKeyId();
|
||||||
this.visibility6 = bwv[6].visibility;
|
this.visibility6 = bwv[6].visibility;
|
||||||
}
|
}
|
||||||
if (length > 7) {
|
if (length > 7) {
|
||||||
this.binding7 = bwv[7].binding;
|
this.provider7 = bwv[7].provider;
|
||||||
this.keyId7 = bwv[7].getKeyId();
|
this.keyId7 = bwv[7].getKeyId();
|
||||||
this.visibility7 = bwv[7].visibility;
|
this.visibility7 = bwv[7].visibility;
|
||||||
}
|
}
|
||||||
if (length > 8) {
|
if (length > 8) {
|
||||||
this.binding8 = bwv[8].binding;
|
this.provider8 = bwv[8].provider;
|
||||||
this.keyId8 = bwv[8].getKeyId();
|
this.keyId8 = bwv[8].getKeyId();
|
||||||
this.visibility8 = bwv[8].visibility;
|
this.visibility8 = bwv[8].visibility;
|
||||||
}
|
}
|
||||||
if (length > 9) {
|
if (length > 9) {
|
||||||
this.binding9 = bwv[9].binding;
|
this.provider9 = bwv[9].provider;
|
||||||
this.keyId9 = bwv[9].getKeyId();
|
this.keyId9 = bwv[9].getKeyId();
|
||||||
this.visibility9 = bwv[9].visibility;
|
this.visibility9 = bwv[9].visibility;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
getBindingAtIndex(index: number): any {
|
getProviderAtIndex(index: number): any {
|
||||||
if (index == 0) return this.binding0;
|
if (index == 0) return this.provider0;
|
||||||
if (index == 1) return this.binding1;
|
if (index == 1) return this.provider1;
|
||||||
if (index == 2) return this.binding2;
|
if (index == 2) return this.provider2;
|
||||||
if (index == 3) return this.binding3;
|
if (index == 3) return this.provider3;
|
||||||
if (index == 4) return this.binding4;
|
if (index == 4) return this.provider4;
|
||||||
if (index == 5) return this.binding5;
|
if (index == 5) return this.provider5;
|
||||||
if (index == 6) return this.binding6;
|
if (index == 6) return this.provider6;
|
||||||
if (index == 7) return this.binding7;
|
if (index == 7) return this.provider7;
|
||||||
if (index == 8) return this.binding8;
|
if (index == 8) return this.provider8;
|
||||||
if (index == 9) return this.binding9;
|
if (index == 9) return this.provider9;
|
||||||
throw new OutOfBoundsError(index);
|
throw new OutOfBoundsError(index);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -165,29 +164,29 @@ export class ProtoInjectorInlineStrategy implements ProtoInjectorStrategy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class ProtoInjectorDynamicStrategy implements ProtoInjectorStrategy {
|
export class ProtoInjectorDynamicStrategy implements ProtoInjectorStrategy {
|
||||||
bindings: ResolvedBinding[];
|
providers: ResolvedProvider[];
|
||||||
keyIds: number[];
|
keyIds: number[];
|
||||||
visibilities: Visibility[];
|
visibilities: Visibility[];
|
||||||
|
|
||||||
constructor(protoInj: ProtoInjector, bwv: BindingWithVisibility[]) {
|
constructor(protoInj: ProtoInjector, bwv: ProviderWithVisibility[]) {
|
||||||
var len = bwv.length;
|
var len = bwv.length;
|
||||||
|
|
||||||
this.bindings = ListWrapper.createFixedSize(len);
|
this.providers = ListWrapper.createFixedSize(len);
|
||||||
this.keyIds = ListWrapper.createFixedSize(len);
|
this.keyIds = ListWrapper.createFixedSize(len);
|
||||||
this.visibilities = ListWrapper.createFixedSize(len);
|
this.visibilities = ListWrapper.createFixedSize(len);
|
||||||
|
|
||||||
for (var i = 0; i < len; i++) {
|
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.keyIds[i] = bwv[i].getKeyId();
|
||||||
this.visibilities[i] = bwv[i].visibility;
|
this.visibilities[i] = bwv[i].visibility;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
getBindingAtIndex(index: number): any {
|
getProviderAtIndex(index: number): any {
|
||||||
if (index < 0 || index >= this.bindings.length) {
|
if (index < 0 || index >= this.providers.length) {
|
||||||
throw new OutOfBoundsError(index);
|
throw new OutOfBoundsError(index);
|
||||||
}
|
}
|
||||||
return this.bindings[index];
|
return this.providers[index];
|
||||||
}
|
}
|
||||||
|
|
||||||
createInjectorStrategy(ei: Injector): InjectorStrategy {
|
createInjectorStrategy(ei: Injector): InjectorStrategy {
|
||||||
@ -198,16 +197,16 @@ export class ProtoInjectorDynamicStrategy implements ProtoInjectorStrategy {
|
|||||||
export class ProtoInjector {
|
export class ProtoInjector {
|
||||||
/** @internal */
|
/** @internal */
|
||||||
_strategy: ProtoInjectorStrategy;
|
_strategy: ProtoInjectorStrategy;
|
||||||
numberOfBindings: number;
|
numberOfProviders: number;
|
||||||
|
|
||||||
constructor(bwv: BindingWithVisibility[]) {
|
constructor(bwv: ProviderWithVisibility[]) {
|
||||||
this.numberOfBindings = bwv.length;
|
this.numberOfProviders = bwv.length;
|
||||||
this._strategy = bwv.length > _MAX_CONSTRUCTION_COUNTER ?
|
this._strategy = bwv.length > _MAX_CONSTRUCTION_COUNTER ?
|
||||||
new ProtoInjectorDynamicStrategy(this, bwv) :
|
new ProtoInjectorDynamicStrategy(this, bwv) :
|
||||||
new ProtoInjectorInlineStrategy(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;
|
attach(parent: Injector, isHost: boolean): void;
|
||||||
resetConstructionCounter(): void;
|
resetConstructionCounter(): void;
|
||||||
instantiateBinding(binding: ResolvedBinding, visibility: Visibility): any;
|
instantiateProvider(provider: ResolvedProvider, visibility: Visibility): any;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class InjectorInlineStrategy implements InjectorStrategy {
|
export class InjectorInlineStrategy implements InjectorStrategy {
|
||||||
@ -238,8 +237,8 @@ export class InjectorInlineStrategy implements InjectorStrategy {
|
|||||||
|
|
||||||
resetConstructionCounter(): void { this.injector._constructionCounter = 0; }
|
resetConstructionCounter(): void { this.injector._constructionCounter = 0; }
|
||||||
|
|
||||||
instantiateBinding(binding: ResolvedBinding, visibility: Visibility): any {
|
instantiateProvider(provider: ResolvedProvider, visibility: Visibility): any {
|
||||||
return this.injector._new(binding, visibility);
|
return this.injector._new(provider, visibility);
|
||||||
}
|
}
|
||||||
|
|
||||||
attach(parent: Injector, isHost: boolean): void {
|
attach(parent: Injector, isHost: boolean): void {
|
||||||
@ -254,61 +253,61 @@ export class InjectorInlineStrategy implements InjectorStrategy {
|
|||||||
|
|
||||||
if (p.keyId0 === keyId && canSee(p.visibility0, visibility)) {
|
if (p.keyId0 === keyId && canSee(p.visibility0, visibility)) {
|
||||||
if (this.obj0 === UNDEFINED) {
|
if (this.obj0 === UNDEFINED) {
|
||||||
this.obj0 = inj._new(p.binding0, p.visibility0);
|
this.obj0 = inj._new(p.provider0, p.visibility0);
|
||||||
}
|
}
|
||||||
return this.obj0;
|
return this.obj0;
|
||||||
}
|
}
|
||||||
if (p.keyId1 === keyId && canSee(p.visibility1, visibility)) {
|
if (p.keyId1 === keyId && canSee(p.visibility1, visibility)) {
|
||||||
if (this.obj1 === UNDEFINED) {
|
if (this.obj1 === UNDEFINED) {
|
||||||
this.obj1 = inj._new(p.binding1, p.visibility1);
|
this.obj1 = inj._new(p.provider1, p.visibility1);
|
||||||
}
|
}
|
||||||
return this.obj1;
|
return this.obj1;
|
||||||
}
|
}
|
||||||
if (p.keyId2 === keyId && canSee(p.visibility2, visibility)) {
|
if (p.keyId2 === keyId && canSee(p.visibility2, visibility)) {
|
||||||
if (this.obj2 === UNDEFINED) {
|
if (this.obj2 === UNDEFINED) {
|
||||||
this.obj2 = inj._new(p.binding2, p.visibility2);
|
this.obj2 = inj._new(p.provider2, p.visibility2);
|
||||||
}
|
}
|
||||||
return this.obj2;
|
return this.obj2;
|
||||||
}
|
}
|
||||||
if (p.keyId3 === keyId && canSee(p.visibility3, visibility)) {
|
if (p.keyId3 === keyId && canSee(p.visibility3, visibility)) {
|
||||||
if (this.obj3 === UNDEFINED) {
|
if (this.obj3 === UNDEFINED) {
|
||||||
this.obj3 = inj._new(p.binding3, p.visibility3);
|
this.obj3 = inj._new(p.provider3, p.visibility3);
|
||||||
}
|
}
|
||||||
return this.obj3;
|
return this.obj3;
|
||||||
}
|
}
|
||||||
if (p.keyId4 === keyId && canSee(p.visibility4, visibility)) {
|
if (p.keyId4 === keyId && canSee(p.visibility4, visibility)) {
|
||||||
if (this.obj4 === UNDEFINED) {
|
if (this.obj4 === UNDEFINED) {
|
||||||
this.obj4 = inj._new(p.binding4, p.visibility4);
|
this.obj4 = inj._new(p.provider4, p.visibility4);
|
||||||
}
|
}
|
||||||
return this.obj4;
|
return this.obj4;
|
||||||
}
|
}
|
||||||
if (p.keyId5 === keyId && canSee(p.visibility5, visibility)) {
|
if (p.keyId5 === keyId && canSee(p.visibility5, visibility)) {
|
||||||
if (this.obj5 === UNDEFINED) {
|
if (this.obj5 === UNDEFINED) {
|
||||||
this.obj5 = inj._new(p.binding5, p.visibility5);
|
this.obj5 = inj._new(p.provider5, p.visibility5);
|
||||||
}
|
}
|
||||||
return this.obj5;
|
return this.obj5;
|
||||||
}
|
}
|
||||||
if (p.keyId6 === keyId && canSee(p.visibility6, visibility)) {
|
if (p.keyId6 === keyId && canSee(p.visibility6, visibility)) {
|
||||||
if (this.obj6 === UNDEFINED) {
|
if (this.obj6 === UNDEFINED) {
|
||||||
this.obj6 = inj._new(p.binding6, p.visibility6);
|
this.obj6 = inj._new(p.provider6, p.visibility6);
|
||||||
}
|
}
|
||||||
return this.obj6;
|
return this.obj6;
|
||||||
}
|
}
|
||||||
if (p.keyId7 === keyId && canSee(p.visibility7, visibility)) {
|
if (p.keyId7 === keyId && canSee(p.visibility7, visibility)) {
|
||||||
if (this.obj7 === UNDEFINED) {
|
if (this.obj7 === UNDEFINED) {
|
||||||
this.obj7 = inj._new(p.binding7, p.visibility7);
|
this.obj7 = inj._new(p.provider7, p.visibility7);
|
||||||
}
|
}
|
||||||
return this.obj7;
|
return this.obj7;
|
||||||
}
|
}
|
||||||
if (p.keyId8 === keyId && canSee(p.visibility8, visibility)) {
|
if (p.keyId8 === keyId && canSee(p.visibility8, visibility)) {
|
||||||
if (this.obj8 === UNDEFINED) {
|
if (this.obj8 === UNDEFINED) {
|
||||||
this.obj8 = inj._new(p.binding8, p.visibility8);
|
this.obj8 = inj._new(p.provider8, p.visibility8);
|
||||||
}
|
}
|
||||||
return this.obj8;
|
return this.obj8;
|
||||||
}
|
}
|
||||||
if (p.keyId9 === keyId && canSee(p.visibility9, visibility)) {
|
if (p.keyId9 === keyId && canSee(p.visibility9, visibility)) {
|
||||||
if (this.obj9 === UNDEFINED) {
|
if (this.obj9 === UNDEFINED) {
|
||||||
this.obj9 = inj._new(p.binding9, p.visibility9);
|
this.obj9 = inj._new(p.provider9, p.visibility9);
|
||||||
}
|
}
|
||||||
return this.obj9;
|
return this.obj9;
|
||||||
}
|
}
|
||||||
@ -338,14 +337,14 @@ export class InjectorDynamicStrategy implements InjectorStrategy {
|
|||||||
objs: any[];
|
objs: any[];
|
||||||
|
|
||||||
constructor(public protoStrategy: ProtoInjectorDynamicStrategy, public injector: Injector) {
|
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);
|
ListWrapper.fill(this.objs, UNDEFINED);
|
||||||
}
|
}
|
||||||
|
|
||||||
resetConstructionCounter(): void { this.injector._constructionCounter = 0; }
|
resetConstructionCounter(): void { this.injector._constructionCounter = 0; }
|
||||||
|
|
||||||
instantiateBinding(binding: ResolvedBinding, visibility: Visibility): any {
|
instantiateProvider(provider: ResolvedProvider, visibility: Visibility): any {
|
||||||
return this.injector._new(binding, visibility);
|
return this.injector._new(provider, visibility);
|
||||||
}
|
}
|
||||||
|
|
||||||
attach(parent: Injector, isHost: boolean): void {
|
attach(parent: Injector, isHost: boolean): void {
|
||||||
@ -360,7 +359,7 @@ export class InjectorDynamicStrategy implements InjectorStrategy {
|
|||||||
for (var i = 0; i < p.keyIds.length; i++) {
|
for (var i = 0; i < p.keyIds.length; i++) {
|
||||||
if (p.keyIds[i] === keyId && canSee(p.visibilities[i], visibility)) {
|
if (p.keyIds[i] === keyId && canSee(p.visibilities[i], visibility)) {
|
||||||
if (this.objs[i] === UNDEFINED) {
|
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];
|
return this.objs[i];
|
||||||
@ -381,17 +380,17 @@ export class InjectorDynamicStrategy implements InjectorStrategy {
|
|||||||
getMaxNumberOfObjects(): number { return this.objs.length; }
|
getMaxNumberOfObjects(): number { return this.objs.length; }
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BindingWithVisibility {
|
export class ProviderWithVisibility {
|
||||||
constructor(public binding: ResolvedBinding, public visibility: Visibility){};
|
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 {
|
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 {
|
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
|
* 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))
|
* ### Example ([live demo](http://plnkr.co/edit/AiXTHi?p=preview))
|
||||||
*
|
*
|
||||||
@ -445,30 +444,30 @@ export class Injector {
|
|||||||
* constructor(public engine:Engine) {}
|
* 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(providers[0] instanceof ResolvedProvider).toBe(true);
|
||||||
* expect(bindings[0].key.displayName).toBe("Car");
|
* expect(providers[0].key.displayName).toBe("Car");
|
||||||
* expect(bindings[0].dependencies.length).toEqual(1);
|
* expect(providers[0].dependencies.length).toEqual(1);
|
||||||
* expect(bindings[0].factory).toBeDefined();
|
* 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[] {
|
static resolve(providers: Array<Type | Provider | any[]>): ResolvedProvider[] {
|
||||||
return resolveBindings(bindings);
|
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},
|
* The passed-in providers can be an array of `Type`, {@link Provider},
|
||||||
* or a recursive array of more bindings.
|
* or a recursive array of more providers.
|
||||||
*
|
*
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/ePOccA?p=preview))
|
* ### 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);
|
* expect(injector.get(Car) instanceof Car).toBe(true);
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
* This function is slower than the corresponding `fromResolvedBindings`
|
* This function is slower than the corresponding `fromResolvedProviders`
|
||||||
* 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 fromResolvedBindings}.
|
* See {@link resolve} and {@link fromResolvedProviders}.
|
||||||
*/
|
*/
|
||||||
static resolveAndCreate(bindings: Array<Type | Binding | any[]>): Injector {
|
static resolveAndCreate(providers: Array<Type | Provider | any[]>): Injector {
|
||||||
var resolvedBindings = Injector.resolve(bindings);
|
var resolvedProviders = Injector.resolve(providers);
|
||||||
return Injector.fromResolvedBindings(resolvedBindings);
|
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.
|
* This API is the recommended way to construct injectors in performance-sensitive parts.
|
||||||
*
|
*
|
||||||
@ -512,17 +511,24 @@ export class Injector {
|
|||||||
* constructor(public engine:Engine) {}
|
* constructor(public engine:Engine) {}
|
||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* var bindings = Injector.resolve([Car, Engine]);
|
* var providers = Injector.resolve([Car, Engine]);
|
||||||
* var injector = Injector.fromResolvedBindings(bindings);
|
* var injector = Injector.fromResolvedProviders(providers);
|
||||||
* expect(injector.get(Car) instanceof Car).toBe(true);
|
* expect(injector.get(Car) instanceof Car).toBe(true);
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
static fromResolvedBindings(bindings: ResolvedBinding[]): Injector {
|
static fromResolvedProviders(providers: ResolvedProvider[]): Injector {
|
||||||
var bd = bindings.map(b => new BindingWithVisibility(b, Visibility.Public));
|
var bd = providers.map(b => new ProviderWithVisibility(b, Visibility.Public));
|
||||||
var proto = new ProtoInjector(bd);
|
var proto = new ProtoInjector(bd);
|
||||||
return new Injector(proto, null, null);
|
return new Injector(proto, null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated
|
||||||
|
*/
|
||||||
|
static fromResolvedBindings(providers: ResolvedProvider[]): Injector {
|
||||||
|
return Injector.fromResolvedProviders(providers);
|
||||||
|
}
|
||||||
|
|
||||||
/** @internal */
|
/** @internal */
|
||||||
_strategy: InjectorStrategy;
|
_strategy: InjectorStrategy;
|
||||||
/** @internal */
|
/** @internal */
|
||||||
@ -551,13 +557,13 @@ export class Injector {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves an instance from the injector based on the provided token.
|
* 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))
|
* ### Example ([live demo](http://plnkr.co/edit/HeXSHg?p=preview))
|
||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* bind("validToken").toValue("Value")
|
* provide("validToken", {asValue: "Value"})
|
||||||
* ]);
|
* ]);
|
||||||
* expect(injector.get("validToken")).toEqual("Value");
|
* expect(injector.get("validToken")).toEqual("Value");
|
||||||
* expect(() => injector.get("invalidToken")).toThrowError();
|
* expect(() => injector.get("invalidToken")).toThrowError();
|
||||||
@ -582,7 +588,7 @@ export class Injector {
|
|||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* bind("validToken").toValue("Value")
|
* provide("validToken", {asValue: "Value"})
|
||||||
* ]);
|
* ]);
|
||||||
* expect(injector.getOptional("validToken")).toEqual("Value");
|
* expect(injector.getOptional("validToken")).toEqual("Value");
|
||||||
* expect(injector.getOptional("invalidToken")).toBe(null);
|
* expect(injector.getOptional("invalidToken")).toBe(null);
|
||||||
@ -628,39 +634,39 @@ export class Injector {
|
|||||||
get internalStrategy(): any { return this._strategy; }
|
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.
|
* <!-- 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},
|
* The passed-in providers can be an array of `Type`, {@link Provider},
|
||||||
* or a recursive array of more bindings.
|
* or a recursive array of more providers.
|
||||||
*
|
*
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/opB3T4?p=preview))
|
* ### Example ([live demo](http://plnkr.co/edit/opB3T4?p=preview))
|
||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* class ParentBinding {}
|
* class ParentProvider {}
|
||||||
* class ChildBinding {}
|
* class ChildProvider {}
|
||||||
*
|
*
|
||||||
* var parent = Injector.resolveAndCreate([ParentBinding]);
|
* var parent = Injector.resolveAndCreate([ParentProvider]);
|
||||||
* var child = parent.resolveAndCreateChild([ChildBinding]);
|
* var child = parent.resolveAndCreateChild([ChildProvider]);
|
||||||
*
|
*
|
||||||
* expect(child.get(ParentBinding) instanceof ParentBinding).toBe(true);
|
* expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);
|
||||||
* expect(child.get(ChildBinding) instanceof ChildBinding).toBe(true);
|
* expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);
|
||||||
* expect(child.get(ParentBinding)).toBe(parent.get(ParentBinding));
|
* expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
* This function is slower than the corresponding `createChildFromResolved`
|
* 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}.
|
* See {@link resolve} and {@link createChildFromResolved}.
|
||||||
*/
|
*/
|
||||||
resolveAndCreateChild(bindings: Array<Type | Binding | any[]>): Injector {
|
resolveAndCreateChild(providers: Array<Type | Provider | any[]>): Injector {
|
||||||
var resolvedBindings = Injector.resolve(bindings);
|
var resolvedProviders = Injector.resolve(providers);
|
||||||
return this.createChildFromResolved(resolvedBindings);
|
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.
|
* <!-- 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))
|
* ### Example ([live demo](http://plnkr.co/edit/VhyfjN?p=preview))
|
||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* class ParentBinding {}
|
* class ParentProvider {}
|
||||||
* class ChildBinding {}
|
* class ChildProvider {}
|
||||||
*
|
*
|
||||||
* var parentBindings = Injector.resolve([ParentBinding]);
|
* var parentProviders = Injector.resolve([ParentProvider]);
|
||||||
* var childBindings = Injector.resolve([ChildBinding]);
|
* var childProviders = Injector.resolve([ChildProvider]);
|
||||||
*
|
*
|
||||||
* var parent = Injector.fromResolvedBindings(parentBindings);
|
* var parent = Injector.fromResolvedProviders(parentProviders);
|
||||||
* var child = parent.createChildFromResolved(childBindings);
|
* var child = parent.createChildFromResolved(childProviders);
|
||||||
*
|
*
|
||||||
* expect(child.get(ParentBinding) instanceof ParentBinding).toBe(true);
|
* expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);
|
||||||
* expect(child.get(ChildBinding) instanceof ChildBinding).toBe(true);
|
* expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);
|
||||||
* expect(child.get(ParentBinding)).toBe(parent.get(ParentBinding));
|
* expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
createChildFromResolved(bindings: ResolvedBinding[]): Injector {
|
createChildFromResolved(providers: ResolvedProvider[]): Injector {
|
||||||
var bd = bindings.map(b => new BindingWithVisibility(b, Visibility.Public));
|
var bd = providers.map(b => new ProviderWithVisibility(b, Visibility.Public));
|
||||||
var proto = new ProtoInjector(bd);
|
var proto = new ProtoInjector(bd);
|
||||||
var inj = new Injector(proto, null, null);
|
var inj = new Injector(proto, null, null);
|
||||||
inj._parent = this;
|
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.
|
* The created object does not get cached by the injector.
|
||||||
*
|
*
|
||||||
@ -716,12 +722,12 @@ export class Injector {
|
|||||||
* expect(car).not.toBe(injector.resolveAndInstantiate(Car));
|
* expect(car).not.toBe(injector.resolveAndInstantiate(Car));
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
resolveAndInstantiate(binding: Type | Binding): any {
|
resolveAndInstantiate(provider: Type | Provider): any {
|
||||||
return this.instantiateResolved(Injector.resolve([binding])[0]);
|
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.
|
* The created object does not get cached by the injector.
|
||||||
*
|
*
|
||||||
@ -738,37 +744,37 @@ export class Injector {
|
|||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* var injector = Injector.resolveAndCreate([Engine]);
|
* var injector = Injector.resolveAndCreate([Engine]);
|
||||||
* var carBinding = Injector.resolve([Car])[0];
|
* var carProvider = Injector.resolve([Car])[0];
|
||||||
* var car = injector.instantiateResolved(carBinding);
|
* var car = injector.instantiateResolved(carProvider);
|
||||||
* expect(car.engine).toBe(injector.get(Engine));
|
* 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 {
|
instantiateResolved(provider: ResolvedProvider): any {
|
||||||
return this._instantiateBinding(binding, Visibility.PublicAndPrivate);
|
return this._instantiateProvider(provider, Visibility.PublicAndPrivate);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @internal */
|
/** @internal */
|
||||||
_new(binding: ResolvedBinding, visibility: Visibility): any {
|
_new(provider: ResolvedProvider, visibility: Visibility): any {
|
||||||
if (this._constructionCounter++ > this._strategy.getMaxNumberOfObjects()) {
|
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 {
|
private _instantiateProvider(provider: ResolvedProvider, visibility: Visibility): any {
|
||||||
if (binding.multiBinding) {
|
if (provider.multiProvider) {
|
||||||
var res = ListWrapper.createFixedSize(binding.resolvedFactories.length);
|
var res = ListWrapper.createFixedSize(provider.resolvedFactories.length);
|
||||||
for (var i = 0; i < binding.resolvedFactories.length; ++i) {
|
for (var i = 0; i < provider.resolvedFactories.length; ++i) {
|
||||||
res[i] = this._instantiate(binding, binding.resolvedFactories[i], visibility);
|
res[i] = this._instantiate(provider, provider.resolvedFactories[i], visibility);
|
||||||
}
|
}
|
||||||
return res;
|
return res;
|
||||||
} else {
|
} 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 {
|
visibility: Visibility): any {
|
||||||
var factory = resolvedFactory.factory;
|
var factory = resolvedFactory.factory;
|
||||||
var deps = resolvedFactory.dependencies;
|
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;
|
var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19;
|
||||||
try {
|
try {
|
||||||
d0 = length > 0 ? this._getByDependency(binding, deps[0], visibility) : null;
|
d0 = length > 0 ? this._getByDependency(provider, deps[0], visibility) : null;
|
||||||
d1 = length > 1 ? this._getByDependency(binding, deps[1], visibility) : null;
|
d1 = length > 1 ? this._getByDependency(provider, deps[1], visibility) : null;
|
||||||
d2 = length > 2 ? this._getByDependency(binding, deps[2], visibility) : null;
|
d2 = length > 2 ? this._getByDependency(provider, deps[2], visibility) : null;
|
||||||
d3 = length > 3 ? this._getByDependency(binding, deps[3], visibility) : null;
|
d3 = length > 3 ? this._getByDependency(provider, deps[3], visibility) : null;
|
||||||
d4 = length > 4 ? this._getByDependency(binding, deps[4], visibility) : null;
|
d4 = length > 4 ? this._getByDependency(provider, deps[4], visibility) : null;
|
||||||
d5 = length > 5 ? this._getByDependency(binding, deps[5], visibility) : null;
|
d5 = length > 5 ? this._getByDependency(provider, deps[5], visibility) : null;
|
||||||
d6 = length > 6 ? this._getByDependency(binding, deps[6], visibility) : null;
|
d6 = length > 6 ? this._getByDependency(provider, deps[6], visibility) : null;
|
||||||
d7 = length > 7 ? this._getByDependency(binding, deps[7], visibility) : null;
|
d7 = length > 7 ? this._getByDependency(provider, deps[7], visibility) : null;
|
||||||
d8 = length > 8 ? this._getByDependency(binding, deps[8], visibility) : null;
|
d8 = length > 8 ? this._getByDependency(provider, deps[8], visibility) : null;
|
||||||
d9 = length > 9 ? this._getByDependency(binding, deps[9], visibility) : null;
|
d9 = length > 9 ? this._getByDependency(provider, deps[9], visibility) : null;
|
||||||
d10 = length > 10 ? this._getByDependency(binding, deps[10], visibility) : null;
|
d10 = length > 10 ? this._getByDependency(provider, deps[10], visibility) : null;
|
||||||
d11 = length > 11 ? this._getByDependency(binding, deps[11], visibility) : null;
|
d11 = length > 11 ? this._getByDependency(provider, deps[11], visibility) : null;
|
||||||
d12 = length > 12 ? this._getByDependency(binding, deps[12], visibility) : null;
|
d12 = length > 12 ? this._getByDependency(provider, deps[12], visibility) : null;
|
||||||
d13 = length > 13 ? this._getByDependency(binding, deps[13], visibility) : null;
|
d13 = length > 13 ? this._getByDependency(provider, deps[13], visibility) : null;
|
||||||
d14 = length > 14 ? this._getByDependency(binding, deps[14], visibility) : null;
|
d14 = length > 14 ? this._getByDependency(provider, deps[14], visibility) : null;
|
||||||
d15 = length > 15 ? this._getByDependency(binding, deps[15], visibility) : null;
|
d15 = length > 15 ? this._getByDependency(provider, deps[15], visibility) : null;
|
||||||
d16 = length > 16 ? this._getByDependency(binding, deps[16], visibility) : null;
|
d16 = length > 16 ? this._getByDependency(provider, deps[16], visibility) : null;
|
||||||
d17 = length > 17 ? this._getByDependency(binding, deps[17], visibility) : null;
|
d17 = length > 17 ? this._getByDependency(provider, deps[17], visibility) : null;
|
||||||
d18 = length > 18 ? this._getByDependency(binding, deps[18], visibility) : null;
|
d18 = length > 18 ? this._getByDependency(provider, deps[18], visibility) : null;
|
||||||
d19 = length > 19 ? this._getByDependency(binding, deps[19], visibility) : null;
|
d19 = length > 19 ? this._getByDependency(provider, deps[19], visibility) : null;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e instanceof AbstractBindingError || e instanceof InstantiationError) {
|
if (e instanceof AbstractProviderError || e instanceof InstantiationError) {
|
||||||
e.addKey(this, binding.key);
|
e.addKey(this, provider.key);
|
||||||
}
|
}
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
@ -874,38 +880,38 @@ export class Injector {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw new InstantiationError(this, e, e.stack, binding.key);
|
throw new InstantiationError(this, e, e.stack, provider.key);
|
||||||
}
|
}
|
||||||
return obj;
|
return obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _getByDependency(binding: ResolvedBinding, dep: Dependency,
|
private _getByDependency(provider: ResolvedProvider, dep: Dependency,
|
||||||
bindingVisibility: Visibility): any {
|
providerVisibility: Visibility): any {
|
||||||
var special = isPresent(this._depProvider) ?
|
var special = isPresent(this._depProvider) ?
|
||||||
this._depProvider.getDependency(this, binding, dep) :
|
this._depProvider.getDependency(this, provider, dep) :
|
||||||
UNDEFINED;
|
UNDEFINED;
|
||||||
if (special !== UNDEFINED) {
|
if (special !== UNDEFINED) {
|
||||||
return special;
|
return special;
|
||||||
} else {
|
} else {
|
||||||
return this._getByKey(dep.key, dep.lowerBoundVisibility, dep.upperBoundVisibility,
|
return this._getByKey(dep.key, dep.lowerBoundVisibility, dep.upperBoundVisibility,
|
||||||
dep.optional, bindingVisibility);
|
dep.optional, providerVisibility);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private _getByKey(key: Key, lowerBoundVisibility: Object, upperBoundVisibility: Object,
|
private _getByKey(key: Key, lowerBoundVisibility: Object, upperBoundVisibility: Object,
|
||||||
optional: boolean, bindingVisibility: Visibility): any {
|
optional: boolean, providerVisibility: Visibility): any {
|
||||||
if (key === INJECTOR_KEY) {
|
if (key === INJECTOR_KEY) {
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (upperBoundVisibility instanceof SelfMetadata) {
|
if (upperBoundVisibility instanceof SelfMetadata) {
|
||||||
return this._getByKeySelf(key, optional, bindingVisibility);
|
return this._getByKeySelf(key, optional, providerVisibility);
|
||||||
|
|
||||||
} else if (upperBoundVisibility instanceof HostMetadata) {
|
} else if (upperBoundVisibility instanceof HostMetadata) {
|
||||||
return this._getByKeyHost(key, optional, bindingVisibility, lowerBoundVisibility);
|
return this._getByKeyHost(key, optional, providerVisibility, lowerBoundVisibility);
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
return this._getByKeyDefault(key, optional, bindingVisibility, lowerBoundVisibility);
|
return this._getByKeyDefault(key, optional, providerVisibility, lowerBoundVisibility);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -914,18 +920,18 @@ export class Injector {
|
|||||||
if (optional) {
|
if (optional) {
|
||||||
return null;
|
return null;
|
||||||
} else {
|
} else {
|
||||||
throw new NoBindingError(this, key);
|
throw new NoProviderError(this, key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @internal */
|
/** @internal */
|
||||||
_getByKeySelf(key: Key, optional: boolean, bindingVisibility: Visibility): any {
|
_getByKeySelf(key: Key, optional: boolean, providerVisibility: Visibility): any {
|
||||||
var obj = this._strategy.getObjByKeyId(key.id, bindingVisibility);
|
var obj = this._strategy.getObjByKeyId(key.id, providerVisibility);
|
||||||
return (obj !== UNDEFINED) ? obj : this._throwOrNull(key, optional);
|
return (obj !== UNDEFINED) ? obj : this._throwOrNull(key, optional);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @internal */
|
/** @internal */
|
||||||
_getByKeyHost(key: Key, optional: boolean, bindingVisibility: Visibility,
|
_getByKeyHost(key: Key, optional: boolean, providerVisibility: Visibility,
|
||||||
lowerBoundVisibility: Object): any {
|
lowerBoundVisibility: Object): any {
|
||||||
var inj = this;
|
var inj = this;
|
||||||
|
|
||||||
@ -938,7 +944,7 @@ export class Injector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
while (inj != null) {
|
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 (obj !== UNDEFINED) return obj;
|
||||||
|
|
||||||
if (isPresent(inj._parent) && inj._isHost) {
|
if (isPresent(inj._parent) && inj._isHost) {
|
||||||
@ -958,20 +964,20 @@ export class Injector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @internal */
|
/** @internal */
|
||||||
_getByKeyDefault(key: Key, optional: boolean, bindingVisibility: Visibility,
|
_getByKeyDefault(key: Key, optional: boolean, providerVisibility: Visibility,
|
||||||
lowerBoundVisibility: Object): any {
|
lowerBoundVisibility: Object): any {
|
||||||
var inj = this;
|
var inj = this;
|
||||||
|
|
||||||
if (lowerBoundVisibility instanceof SkipSelfMetadata) {
|
if (lowerBoundVisibility instanceof SkipSelfMetadata) {
|
||||||
bindingVisibility = inj._isHost ? Visibility.PublicAndPrivate : Visibility.Public;
|
providerVisibility = inj._isHost ? Visibility.PublicAndPrivate : Visibility.Public;
|
||||||
inj = inj._parent;
|
inj = inj._parent;
|
||||||
}
|
}
|
||||||
|
|
||||||
while (inj != null) {
|
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 (obj !== UNDEFINED) return obj;
|
||||||
|
|
||||||
bindingVisibility = inj._isHost ? Visibility.PublicAndPrivate : Visibility.Public;
|
providerVisibility = inj._isHost ? Visibility.PublicAndPrivate : Visibility.Public;
|
||||||
inj = inj._parent;
|
inj = inj._parent;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -979,7 +985,7 @@ export class Injector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get displayName(): string {
|
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; }
|
toString(): string { return this.displayName; }
|
||||||
@ -988,10 +994,10 @@ export class Injector {
|
|||||||
var INJECTOR_KEY = Key.get(Injector);
|
var INJECTOR_KEY = Key.get(Injector);
|
||||||
|
|
||||||
|
|
||||||
function _mapBindings(injector: Injector, fn: Function): any[] {
|
function _mapProviders(injector: Injector, fn: Function): any[] {
|
||||||
var res = [];
|
var res = [];
|
||||||
for (var i = 0; i < injector._proto.numberOfBindings; ++i) {
|
for (var i = 0; i < injector._proto.numberOfProviders; ++i) {
|
||||||
res.push(fn(injector._proto.getBindingAtIndex(i)));
|
res.push(fn(injector._proto.getProviderAtIndex(i)));
|
||||||
}
|
}
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
@ -16,7 +16,7 @@ export {TypeLiteral} from './type_literal';
|
|||||||
* injector to store created objects in a more efficient way.
|
* injector to store created objects in a more efficient way.
|
||||||
*
|
*
|
||||||
* `Key` should not be created directly. {@link Injector} creates keys automatically when resolving
|
* `Key` should not be created directly. {@link Injector} creates keys automatically when resolving
|
||||||
* bindings.
|
* providers.
|
||||||
*/
|
*/
|
||||||
export class Key {
|
export class Key {
|
||||||
/**
|
/**
|
||||||
|
@ -17,7 +17,7 @@ import {CONST, CONST_EXPR, stringify, isBlank, isPresent} from "angular2/src/cor
|
|||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* bind("MyEngine").toClass(Engine),
|
* provide("MyEngine", {asClass: Engine}),
|
||||||
* Car
|
* Car
|
||||||
* ]);
|
* ]);
|
||||||
*
|
*
|
||||||
@ -212,7 +212,7 @@ export class SkipSelfMetadata {
|
|||||||
*
|
*
|
||||||
* @Component({
|
* @Component({
|
||||||
* selector: 'parent-cmp',
|
* selector: 'parent-cmp',
|
||||||
* bindings: [HostService]
|
* providers: [HostService]
|
||||||
* })
|
* })
|
||||||
* @View({
|
* @View({
|
||||||
* template: `
|
* template: `
|
||||||
@ -225,7 +225,7 @@ export class SkipSelfMetadata {
|
|||||||
*
|
*
|
||||||
* @Component({
|
* @Component({
|
||||||
* selector: 'app',
|
* selector: 'app',
|
||||||
* bindings: [OtherService]
|
* providers: [OtherService]
|
||||||
* })
|
* })
|
||||||
* @View({
|
* @View({
|
||||||
* template: `
|
* template: `
|
||||||
|
@ -1,22 +1,22 @@
|
|||||||
import {CONST} from 'angular2/src/core/facade/lang';
|
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))
|
* ### Example ([live demo](http://plnkr.co/edit/Ys9ezXpj2Mnoy3Uc8KBp?p=preview))
|
||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* var t = new OpaqueToken("binding");
|
* var t = new OpaqueToken("value");
|
||||||
*
|
*
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* bind(t).toValue("bindingValue")
|
* provide(t, {asValue: "providedValue"})
|
||||||
* ]);
|
* ]);
|
||||||
*
|
*
|
||||||
* expect(injector.get(t)).toEqual("bindingValue");
|
* expect(injector.get(t)).toEqual("bindingValue");
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
* Using an `OpaqueToken` is preferable to using strings as tokens because of possible collisions
|
* 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
|
* Using an `OpaqueToken` is preferable to using an `Object` as tokens because it provides better
|
||||||
* error messages.
|
* error messages.
|
||||||
|
@ -25,8 +25,8 @@ import {
|
|||||||
} from './metadata';
|
} from './metadata';
|
||||||
import {
|
import {
|
||||||
NoAnnotationError,
|
NoAnnotationError,
|
||||||
MixingMultiBindingsWithRegularBindings,
|
MixingMultiProvidersWithRegularProvidersError,
|
||||||
InvalidBindingError
|
InvalidProviderError
|
||||||
} from './exceptions';
|
} from './exceptions';
|
||||||
import {resolveForwardRef} from './forward_ref';
|
import {resolveForwardRef} from './forward_ref';
|
||||||
|
|
||||||
@ -42,22 +42,22 @@ const _EMPTY_LIST = CONST_EXPR([]);
|
|||||||
/**
|
/**
|
||||||
* Describes how the {@link Injector} should instantiate a given token.
|
* 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))
|
* ### Example ([live demo](http://plnkr.co/edit/GNAyj6K6PfYg2NBzgwZ5?p%3Dpreview&p=preview))
|
||||||
*
|
*
|
||||||
* ```javascript
|
* ```javascript
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* new Binding("message", { toValue: 'Hello' })
|
* new Provider("message", { toValue: 'Hello' })
|
||||||
* ]);
|
* ]);
|
||||||
*
|
*
|
||||||
* expect(injector.get("message")).toEqual('Hello');
|
* expect(injector.get("message")).toEqual('Hello');
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
@CONST()
|
@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;
|
token;
|
||||||
|
|
||||||
@ -77,11 +77,11 @@ export class Binding {
|
|||||||
*
|
*
|
||||||
* var injectorClass = Injector.resolveAndCreate([
|
* var injectorClass = Injector.resolveAndCreate([
|
||||||
* Car,
|
* Car,
|
||||||
* new Binding(Vehicle, { toClass: Car })
|
* new Provider(Vehicle, { toClass: Car })
|
||||||
* ]);
|
* ]);
|
||||||
* var injectorAlias = Injector.resolveAndCreate([
|
* var injectorAlias = Injector.resolveAndCreate([
|
||||||
* Car,
|
* Car,
|
||||||
* new Binding(Vehicle, { toAlias: Car })
|
* new Provider(Vehicle, { toAlias: Car })
|
||||||
* ]);
|
* ]);
|
||||||
*
|
*
|
||||||
* expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
|
* expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
|
||||||
@ -100,7 +100,7 @@ export class Binding {
|
|||||||
*
|
*
|
||||||
* ```javascript
|
* ```javascript
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* new Binding("message", { toValue: 'Hello' })
|
* new Provider("message", { toValue: 'Hello' })
|
||||||
* ]);
|
* ]);
|
||||||
*
|
*
|
||||||
* expect(injector.get("message")).toEqual('Hello');
|
* expect(injector.get("message")).toEqual('Hello');
|
||||||
@ -126,11 +126,11 @@ export class Binding {
|
|||||||
*
|
*
|
||||||
* var injectorAlias = Injector.resolveAndCreate([
|
* var injectorAlias = Injector.resolveAndCreate([
|
||||||
* Car,
|
* Car,
|
||||||
* new Binding(Vehicle, { toAlias: Car })
|
* new Provider(Vehicle, { toAlias: Car })
|
||||||
* ]);
|
* ]);
|
||||||
* var injectorClass = Injector.resolveAndCreate([
|
* var injectorClass = Injector.resolveAndCreate([
|
||||||
* Car,
|
* Car,
|
||||||
* new Binding(Vehicle, { toClass: Car })
|
* new Provider(Vehicle, { toClass: Car })
|
||||||
* ]);
|
* ]);
|
||||||
*
|
*
|
||||||
* expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
|
* expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
|
||||||
@ -149,8 +149,8 @@ export class Binding {
|
|||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* new Binding(Number, { toFactory: () => { return 1+2; }}),
|
* new Provider(Number, { toFactory: () => { return 1+2; }}),
|
||||||
* new Binding(String, { toFactory: (value) => { return "Value: " + value; },
|
* new Provider(String, { toFactory: (value) => { return "Value: " + value; },
|
||||||
* deps: [Number] })
|
* deps: [Number] })
|
||||||
* ]);
|
* ]);
|
||||||
*
|
*
|
||||||
@ -170,8 +170,8 @@ export class Binding {
|
|||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* new Binding(Number, { toFactory: () => { return 1+2; }}),
|
* new Provider(Number, { toFactory: () => { return 1+2; }}),
|
||||||
* new Binding(String, { toFactory: (value) => { return "Value: " + value; },
|
* new Provider(String, { toFactory: (value) => { return "Value: " + value; },
|
||||||
* deps: [Number] })
|
* deps: [Number] })
|
||||||
* ]);
|
* ]);
|
||||||
*
|
*
|
||||||
@ -205,40 +205,63 @@ export class Binding {
|
|||||||
|
|
||||||
// TODO: Provide a full working example after alpha38 is released.
|
// 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
|
* Multi-providers are used for creating pluggable service, where the system comes
|
||||||
* with some default bindings, and the user can register additonal bindings.
|
* with some default providers, and the user can register additonal providers.
|
||||||
* The combination of the default bindings and the additional bindings will be
|
* The combination of the default providers and the additional providers will be
|
||||||
* used to drive the behavior of the system.
|
* used to drive the behavior of the system.
|
||||||
*
|
*
|
||||||
* ### Example
|
* ### Example
|
||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* new Binding("Strings", { toValue: "String1", multi: true}),
|
* new Provider("Strings", { toValue: "String1", multi: true}),
|
||||||
* new Binding("Strings", { toValue: "String2", multi: true})
|
* new Provider("Strings", { toValue: "String2", multi: true})
|
||||||
* ]);
|
* ]);
|
||||||
*
|
*
|
||||||
* expect(injector.get("Strings")).toEqual(["String1", "String2"]);
|
* 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:
|
* will throw an exception:
|
||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* new Binding("Strings", { toValue: "String1", multi: true }),
|
* new Provider("Strings", { toValue: "String1", multi: true }),
|
||||||
* new Binding("Strings", { toValue: "String2"})
|
* new Provider("Strings", { toValue: "String2"})
|
||||||
* ]);
|
* ]);
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
get multi(): boolean { return normalizeBool(this._multi); }
|
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`.
|
* 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))
|
* ### Example ([live demo](http://plnkr.co/edit/RfEnhh8kUEI0G3qsnIeT?p%3Dpreview&p=preview))
|
||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* var resolvedBindings = Injector.resolve([new Binding('message', {toValue: 'Hello'})]);
|
* var resolvedProviders = Injector.resolve([new Provider('message', {toValue: 'Hello'})]);
|
||||||
* var injector = Injector.fromResolvedBindings(resolvedBindings);
|
* var injector = Injector.fromResolvedProviders(resolvedProviders);
|
||||||
*
|
*
|
||||||
* expect(injector.get('message')).toEqual('Hello');
|
* expect(injector.get('message')).toEqual('Hello');
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
export interface ResolvedBinding {
|
export interface ResolvedProvider {
|
||||||
/**
|
/**
|
||||||
* A key, usually a `Type`.
|
* A key, usually a `Type`.
|
||||||
*/
|
*/
|
||||||
@ -265,20 +288,25 @@ export interface ResolvedBinding {
|
|||||||
resolvedFactories: ResolvedFactory[];
|
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[],
|
constructor(public key: Key, public resolvedFactories: ResolvedFactory[],
|
||||||
public multiBinding: boolean) {}
|
public multiProvider: boolean) {}
|
||||||
|
|
||||||
get resolvedFactory(): ResolvedFactory { return this.resolvedFactories[0]; }
|
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 {
|
export class ResolvedFactory {
|
||||||
constructor(
|
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`.
|
* 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}.
|
* The `token` is most commonly a class or {@link angular2/di/OpaqueToken}.
|
||||||
*/
|
*/
|
||||||
export function bind(token): BindingBuilder {
|
export function bind(token): ProviderBuilder {
|
||||||
return new BindingBuilder(token);
|
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.
|
* Helper class for the {@link bind} function.
|
||||||
*/
|
*/
|
||||||
export class BindingBuilder {
|
export class ProviderBuilder {
|
||||||
constructor(public token) {}
|
constructor(public token) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -327,11 +382,11 @@ export class BindingBuilder {
|
|||||||
*
|
*
|
||||||
* var injectorClass = Injector.resolveAndCreate([
|
* var injectorClass = Injector.resolveAndCreate([
|
||||||
* Car,
|
* Car,
|
||||||
* bind(Vehicle).toClass(Car)
|
* provide(Vehicle, {asClass: Car})
|
||||||
* ]);
|
* ]);
|
||||||
* var injectorAlias = Injector.resolveAndCreate([
|
* var injectorAlias = Injector.resolveAndCreate([
|
||||||
* Car,
|
* Car,
|
||||||
* bind(Vehicle).toAlias(Car)
|
* provide(Vehicle, {asAlias: Car})
|
||||||
* ]);
|
* ]);
|
||||||
*
|
*
|
||||||
* expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(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);
|
* expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
toClass(type: Type): Binding {
|
toClass(type: Type): Provider {
|
||||||
if (!isType(type)) {
|
if (!isType(type)) {
|
||||||
throw new BaseException(
|
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
|
* ```typescript
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* bind('message').toValue('Hello')
|
* provide('message', {asValue: 'Hello'})
|
||||||
* ]);
|
* ]);
|
||||||
*
|
*
|
||||||
* expect(injector.get('message')).toEqual('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.
|
* Binds a DI token as an alias for an existing token.
|
||||||
@ -383,11 +438,11 @@ export class BindingBuilder {
|
|||||||
*
|
*
|
||||||
* var injectorAlias = Injector.resolveAndCreate([
|
* var injectorAlias = Injector.resolveAndCreate([
|
||||||
* Car,
|
* Car,
|
||||||
* bind(Vehicle).toAlias(Car)
|
* provide(Vehicle, {asAlias: Car})
|
||||||
* ]);
|
* ]);
|
||||||
* var injectorClass = Injector.resolveAndCreate([
|
* var injectorClass = Injector.resolveAndCreate([
|
||||||
* Car,
|
* Car,
|
||||||
* bind(Vehicle).toClass(Car)
|
* provide(Vehicle, {asClass: Car})
|
||||||
* ]);
|
* ]);
|
||||||
*
|
*
|
||||||
* expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
|
* expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
|
||||||
@ -397,11 +452,11 @@ export class BindingBuilder {
|
|||||||
* expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);
|
* expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
toAlias(aliasToken: /*Type*/ any): Binding {
|
toAlias(aliasToken: /*Type*/ any): Provider {
|
||||||
if (isBlank(aliasToken)) {
|
if (isBlank(aliasToken)) {
|
||||||
throw new BaseException(`Can not alias ${stringify(this.token)} to a blank value!`);
|
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
|
* ```typescript
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* bind(Number).toFactory(() => { return 1+2; }),
|
* provide(Number, {asFactory: () => { return 1+2; }}),
|
||||||
* bind(String).toFactory((v) => { return "Value: " + v; }, [Number])
|
* provide(String, {asFactory: (v) => { return "Value: " + v; }, deps: [Number]})
|
||||||
* ]);
|
* ]);
|
||||||
*
|
*
|
||||||
* expect(injector.get(Number)).toEqual(3);
|
* expect(injector.get(Number)).toEqual(3);
|
||||||
* expect(injector.get(String)).toEqual('Value: 3');
|
* expect(injector.get(String)).toEqual('Value: 3');
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
toFactory(factory: Function, dependencies?: any[]): Binding {
|
toFactory(factory: Function, dependencies?: any[]): Provider {
|
||||||
if (!isFunction(factory)) {
|
if (!isFunction(factory)) {
|
||||||
throw new BaseException(
|
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 factoryFn: Function;
|
||||||
var resolvedDeps;
|
var resolvedDeps;
|
||||||
if (isPresent(binding.toClass)) {
|
if (isPresent(provider.toClass)) {
|
||||||
var toClass = resolveForwardRef(binding.toClass);
|
var toClass = resolveForwardRef(provider.toClass);
|
||||||
factoryFn = reflector.factory(toClass);
|
factoryFn = reflector.factory(toClass);
|
||||||
resolvedDeps = _dependenciesFor(toClass);
|
resolvedDeps = _dependenciesFor(toClass);
|
||||||
} else if (isPresent(binding.toAlias)) {
|
} else if (isPresent(provider.toAlias)) {
|
||||||
factoryFn = (aliasInstance) => aliasInstance;
|
factoryFn = (aliasInstance) => aliasInstance;
|
||||||
resolvedDeps = [Dependency.fromKey(Key.get(binding.toAlias))];
|
resolvedDeps = [Dependency.fromKey(Key.get(provider.toAlias))];
|
||||||
} else if (isPresent(binding.toFactory)) {
|
} else if (isPresent(provider.toFactory)) {
|
||||||
factoryFn = binding.toFactory;
|
factoryFn = provider.toFactory;
|
||||||
resolvedDeps = _constructDependencies(binding.toFactory, binding.dependencies);
|
resolvedDeps = _constructDependencies(provider.toFactory, provider.dependencies);
|
||||||
} else {
|
} else {
|
||||||
factoryFn = () => binding.toValue;
|
factoryFn = () => provider.toValue;
|
||||||
resolvedDeps = _EMPTY_LIST;
|
resolvedDeps = _EMPTY_LIST;
|
||||||
}
|
}
|
||||||
return new ResolvedFactory(factoryFn, resolvedDeps);
|
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
|
* {@link Injector} internally only uses {@link ResolvedProvider}, {@link Provider} contains
|
||||||
* convenience binding syntax.
|
* convenience provider syntax.
|
||||||
*/
|
*/
|
||||||
export function resolveBinding(binding: Binding): ResolvedBinding {
|
export function resolveProvider(provider: Provider): ResolvedProvider {
|
||||||
return new ResolvedBinding_(Key.get(binding.token), [resolveFactory(binding)], false);
|
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[] {
|
export function resolveProviders(providers: Array<Type | Provider | any[]>): ResolvedProvider[] {
|
||||||
var normalized = _createListOfBindings(
|
var normalized = _createListOfProviders(_normalizeProviders(
|
||||||
_normalizeBindings(bindings, new Map<number, _NormalizedBinding | _NormalizedBinding[]>()));
|
providers, new Map<number, _NormalizedProvider | _NormalizedProvider[]>()));
|
||||||
return normalized.map(b => {
|
return normalized.map(b => {
|
||||||
if (b instanceof _NormalizedBinding) {
|
if (b instanceof _NormalizedProvider) {
|
||||||
return new ResolvedBinding_(b.key, [b.resolvedFactory], false);
|
return new ResolvedProvider_(b.key, [b.resolvedFactory], false);
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
var arr = <_NormalizedBinding[]>b;
|
var arr = <_NormalizedProvider[]>b;
|
||||||
return new ResolvedBinding_(arr[0].key, arr.map(_ => _.resolvedFactory), true);
|
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:
|
* 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) {}
|
constructor(public key: Key, public resolvedFactory: ResolvedFactory) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
function _createListOfBindings(flattenedBindings: Map<number, any>): any[] {
|
function _createListOfProviders(flattenedProviders: Map<number, any>): any[] {
|
||||||
return MapWrapper.values(flattenedBindings);
|
return MapWrapper.values(flattenedProviders);
|
||||||
}
|
}
|
||||||
|
|
||||||
function _normalizeBindings(bindings: Array<Type | Binding | BindingBuilder | any[]>,
|
function _normalizeProviders(providers: Array<Type | Provider | ProviderBuilder | any[]>,
|
||||||
res: Map<number, _NormalizedBinding | _NormalizedBinding[]>):
|
res: Map<number, _NormalizedProvider | _NormalizedProvider[]>):
|
||||||
Map<number, _NormalizedBinding | _NormalizedBinding[]> {
|
Map<number, _NormalizedProvider | _NormalizedProvider[]> {
|
||||||
bindings.forEach(b => {
|
providers.forEach(b => {
|
||||||
if (b instanceof Type) {
|
if (b instanceof Type) {
|
||||||
_normalizeBinding(bind(b).toClass(b), res);
|
_normalizeProvider(provide(b, {asClass: b}), res);
|
||||||
|
|
||||||
} else if (b instanceof Binding) {
|
} else if (b instanceof Provider) {
|
||||||
_normalizeBinding(b, res);
|
_normalizeProvider(b, res);
|
||||||
|
|
||||||
} else if (b instanceof Array) {
|
} else if (b instanceof Array) {
|
||||||
_normalizeBindings(b, res);
|
_normalizeProviders(b, res);
|
||||||
|
|
||||||
} else if (b instanceof BindingBuilder) {
|
} else if (b instanceof ProviderBuilder) {
|
||||||
throw new InvalidBindingError(b.token);
|
throw new InvalidProviderError(b.token);
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
throw new InvalidBindingError(b);
|
throw new InvalidProviderError(b);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
function _normalizeBinding(b: Binding, res: Map<number, _NormalizedBinding | _NormalizedBinding[]>):
|
function _normalizeProvider(b: Provider,
|
||||||
void {
|
res: Map<number, _NormalizedProvider | _NormalizedProvider[]>): void {
|
||||||
var key = Key.get(b.token);
|
var key = Key.get(b.token);
|
||||||
var factory = resolveFactory(b);
|
var factory = resolveFactory(b);
|
||||||
var normalized = new _NormalizedBinding(key, factory);
|
var normalized = new _NormalizedProvider(key, factory);
|
||||||
|
|
||||||
if (b.multi) {
|
if (b.multi) {
|
||||||
var existingBinding = res.get(key.id);
|
var existingProvider = res.get(key.id);
|
||||||
|
|
||||||
if (existingBinding instanceof Array) {
|
if (existingProvider instanceof Array) {
|
||||||
existingBinding.push(normalized);
|
existingProvider.push(normalized);
|
||||||
|
|
||||||
} else if (isBlank(existingBinding)) {
|
} else if (isBlank(existingProvider)) {
|
||||||
res.set(key.id, [normalized]);
|
res.set(key.id, [normalized]);
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
throw new MixingMultiBindingsWithRegularBindings(existingBinding, b);
|
throw new MixingMultiProvidersWithRegularProvidersError(existingProvider, b);
|
||||||
}
|
}
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
var existingBinding = res.get(key.id);
|
var existingProvider = res.get(key.id);
|
||||||
|
|
||||||
if (existingBinding instanceof Array) {
|
if (existingProvider instanceof Array) {
|
||||||
throw new MixingMultiBindingsWithRegularBindings(existingBinding, b);
|
throw new MixingMultiProvidersWithRegularProvidersError(existingProvider, b);
|
||||||
}
|
}
|
||||||
|
|
||||||
res.set(key.id, normalized);
|
res.set(key.id, normalized);
|
@ -27,7 +27,7 @@ class _ArrayLogger {
|
|||||||
* }
|
* }
|
||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* bootstrap(MyApp, [bind(ExceptionHandler).toClass(MyExceptionHandler)])
|
* bootstrap(MyApp, [provide(ExceptionHandler, {asClass: MyExceptionHandler})])
|
||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
|
@ -41,12 +41,17 @@ import {FormBuilder} from './forms/form_builder';
|
|||||||
import {CONST_EXPR, Type} from './facade/lang';
|
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:
|
* ### Example:
|
||||||
*
|
*
|
||||||
* ```typescript
|
* ```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;
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
import {Directive} from 'angular2/src/core/metadata';
|
import {Directive} from 'angular2/src/core/metadata';
|
||||||
import {Renderer} from 'angular2/src/core/render';
|
import {Renderer} from 'angular2/src/core/render';
|
||||||
import {ElementRef} from 'angular2/src/core/linker';
|
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 {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor';
|
||||||
import {CONST_EXPR} from 'angular2/src/core/facade/lang';
|
import {CONST_EXPR} from 'angular2/src/core/facade/lang';
|
||||||
import {setProperty} from './shared';
|
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}));
|
NG_VALUE_ACCESSOR, {toAlias: forwardRef(() => CheckboxControlValueAccessor), multi: true}));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
import {Directive} from 'angular2/src/core/metadata';
|
import {Directive} from 'angular2/src/core/metadata';
|
||||||
import {ElementRef} from 'angular2/src/core/linker';
|
import {ElementRef} from 'angular2/src/core/linker';
|
||||||
import {Renderer} from 'angular2/src/core/render';
|
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 {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor';
|
||||||
import {isBlank, CONST_EXPR} from 'angular2/src/core/facade/lang';
|
import {isBlank, CONST_EXPR} from 'angular2/src/core/facade/lang';
|
||||||
import {setProperty} from './shared';
|
import {setProperty} from './shared';
|
||||||
|
|
||||||
const DEFAULT_VALUE_ACCESSOR = CONST_EXPR(
|
const DEFAULT_VALUE_ACCESSOR = CONST_EXPR(new Provider(
|
||||||
new Binding(NG_VALUE_ACCESSOR, {toAlias: forwardRef(() => DefaultValueAccessor), multi: true}));
|
NG_VALUE_ACCESSOR, {toAlias: forwardRef(() => DefaultValueAccessor), multi: true}));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The default accessor for writing a value and listening to changes that is used by the
|
* The default accessor for writing a value and listening to changes that is used by the
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import {OnInit, OnDestroy} from 'angular2/lifecycle_hooks';
|
import {OnInit, OnDestroy} from 'angular2/lifecycle_hooks';
|
||||||
import {Directive} from 'angular2/src/core/metadata';
|
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 {ListWrapper} from 'angular2/src/core/facade/collection';
|
||||||
import {CONST_EXPR} from 'angular2/src/core/facade/lang';
|
import {CONST_EXPR} from 'angular2/src/core/facade/lang';
|
||||||
|
|
||||||
@ -10,7 +10,7 @@ import {ControlGroup} from '../model';
|
|||||||
import {Form} from './form_interface';
|
import {Form} from './form_interface';
|
||||||
|
|
||||||
const controlGroupBinding =
|
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.
|
* Creates and binds a control group to a DOM element.
|
||||||
|
@ -3,7 +3,7 @@ import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async';
|
|||||||
import {OnChanges, OnDestroy} from 'angular2/lifecycle_hooks';
|
import {OnChanges, OnDestroy} from 'angular2/lifecycle_hooks';
|
||||||
import {SimpleChange} from 'angular2/src/core/change_detection';
|
import {SimpleChange} from 'angular2/src/core/change_detection';
|
||||||
import {Query, Directive} from 'angular2/src/core/metadata';
|
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 {ControlContainer} from './control_container';
|
||||||
import {NgControl} from './ng_control';
|
import {NgControl} from './ng_control';
|
||||||
@ -14,7 +14,7 @@ import {Validators, NG_VALIDATORS} from '../validators';
|
|||||||
|
|
||||||
|
|
||||||
const controlNameBinding =
|
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.
|
* Creates and binds a control with a specified name to a DOM element.
|
||||||
|
@ -7,7 +7,7 @@ import {
|
|||||||
import {StringMapWrapper, ListWrapper} from 'angular2/src/core/facade/collection';
|
import {StringMapWrapper, ListWrapper} from 'angular2/src/core/facade/collection';
|
||||||
import {isPresent, isBlank, CONST_EXPR} from 'angular2/src/core/facade/lang';
|
import {isPresent, isBlank, CONST_EXPR} from 'angular2/src/core/facade/lang';
|
||||||
import {Directive} from 'angular2/src/core/metadata';
|
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 {NgControl} from './ng_control';
|
||||||
import {Form} from './form_interface';
|
import {Form} from './form_interface';
|
||||||
import {NgControlGroup} from './ng_control_group';
|
import {NgControlGroup} from './ng_control_group';
|
||||||
@ -15,8 +15,8 @@ import {ControlContainer} from './control_container';
|
|||||||
import {AbstractControl, ControlGroup, Control} from '../model';
|
import {AbstractControl, ControlGroup, Control} from '../model';
|
||||||
import {setUpControl} from './shared';
|
import {setUpControl} from './shared';
|
||||||
|
|
||||||
const formDirectiveBinding =
|
const formDirectiveProvider =
|
||||||
CONST_EXPR(new Binding(ControlContainer, {toAlias: forwardRef(() => NgForm)}));
|
CONST_EXPR(new Provider(ControlContainer, {toAlias: forwardRef(() => NgForm)}));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* If `NgForm` is bound in a component, `<form>` elements in that component will be
|
* If `NgForm` is bound in a component, `<form>` elements in that component will be
|
||||||
@ -81,7 +81,7 @@ const formDirectiveBinding =
|
|||||||
*/
|
*/
|
||||||
@Directive({
|
@Directive({
|
||||||
selector: 'form:not([ng-no-form]):not([ng-form-model]),ng-form,[ng-form]',
|
selector: 'form:not([ng-no-form]):not([ng-form-model]),ng-form,[ng-form]',
|
||||||
bindings: [formDirectiveBinding],
|
bindings: [formDirectiveProvider],
|
||||||
host: {
|
host: {
|
||||||
'(submit)': 'onSubmit()',
|
'(submit)': 'onSubmit()',
|
||||||
},
|
},
|
||||||
|
@ -3,7 +3,7 @@ import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async';
|
|||||||
import {OnChanges} from 'angular2/lifecycle_hooks';
|
import {OnChanges} from 'angular2/lifecycle_hooks';
|
||||||
import {SimpleChange} from 'angular2/src/core/change_detection';
|
import {SimpleChange} from 'angular2/src/core/change_detection';
|
||||||
import {Query, Directive} from 'angular2/src/core/metadata';
|
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 {NgControl} from './ng_control';
|
||||||
import {Control} from '../model';
|
import {Control} from '../model';
|
||||||
import {Validators, NG_VALIDATORS} from '../validators';
|
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';
|
import {setUpControl, isPropertyUpdated, selectValueAccessor} from './shared';
|
||||||
|
|
||||||
const formControlBinding =
|
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.
|
* Binds an existing {@link Control} to a DOM element.
|
||||||
|
@ -4,7 +4,7 @@ import {ObservableWrapper, EventEmitter} from 'angular2/src/core/facade/async';
|
|||||||
|
|
||||||
import {OnChanges} from 'angular2/lifecycle_hooks';
|
import {OnChanges} from 'angular2/lifecycle_hooks';
|
||||||
import {Directive} from 'angular2/src/core/metadata';
|
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 {NgControl} from './ng_control';
|
||||||
import {NgControlGroup} from './ng_control_group';
|
import {NgControlGroup} from './ng_control_group';
|
||||||
import {ControlContainer} from './control_container';
|
import {ControlContainer} from './control_container';
|
||||||
@ -12,8 +12,8 @@ import {Form} from './form_interface';
|
|||||||
import {Control, ControlGroup} from '../model';
|
import {Control, ControlGroup} from '../model';
|
||||||
import {setUpControl} from './shared';
|
import {setUpControl} from './shared';
|
||||||
|
|
||||||
const formDirectiveBinding =
|
const formDirectiveProvider =
|
||||||
CONST_EXPR(new Binding(ControlContainer, {toAlias: forwardRef(() => NgFormModel)}));
|
CONST_EXPR(new Provider(ControlContainer, {toAlias: forwardRef(() => NgFormModel)}));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Binds an existing control group to a DOM element.
|
* Binds an existing control group to a DOM element.
|
||||||
@ -91,7 +91,7 @@ const formDirectiveBinding =
|
|||||||
*/
|
*/
|
||||||
@Directive({
|
@Directive({
|
||||||
selector: '[ng-form-model]',
|
selector: '[ng-form-model]',
|
||||||
bindings: [formDirectiveBinding],
|
bindings: [formDirectiveProvider],
|
||||||
inputs: ['form: ng-form-model'],
|
inputs: ['form: ng-form-model'],
|
||||||
host: {'(submit)': 'onSubmit()'},
|
host: {'(submit)': 'onSubmit()'},
|
||||||
outputs: ['ngSubmit'],
|
outputs: ['ngSubmit'],
|
||||||
|
@ -3,14 +3,15 @@ import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async';
|
|||||||
import {OnChanges} from 'angular2/lifecycle_hooks';
|
import {OnChanges} from 'angular2/lifecycle_hooks';
|
||||||
import {SimpleChange} from 'angular2/src/core/change_detection';
|
import {SimpleChange} from 'angular2/src/core/change_detection';
|
||||||
import {Query, Directive} from 'angular2/src/core/metadata';
|
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 {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
|
||||||
import {NgControl} from './ng_control';
|
import {NgControl} from './ng_control';
|
||||||
import {Control} from '../model';
|
import {Control} from '../model';
|
||||||
import {Validators, NG_VALIDATORS} from '../validators';
|
import {Validators, NG_VALIDATORS} from '../validators';
|
||||||
import {setUpControl, isPropertyUpdated, selectValueAccessor} from './shared';
|
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.
|
* Binds a domain model to a form control.
|
||||||
|
@ -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 {Renderer} from 'angular2/src/core/render';
|
||||||
import {ElementRef, QueryList} from 'angular2/src/core/linker';
|
import {ElementRef, QueryList} from 'angular2/src/core/linker';
|
||||||
import {Query, Directive} from 'angular2/src/core/metadata';
|
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 {CONST_EXPR} from 'angular2/src/core/facade/lang';
|
||||||
import {setProperty} from './shared';
|
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}));
|
NG_VALUE_ACCESSOR, {toAlias: forwardRef(() => SelectControlValueAccessor), multi: true}));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -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 {CONST_EXPR} from 'angular2/src/core/facade/lang';
|
||||||
import {Directive} from 'angular2/src/core/metadata';
|
import {Directive} from 'angular2/src/core/metadata';
|
||||||
import {Validators, NG_VALIDATORS} from '../validators';
|
import {Validators, NG_VALIDATORS} from '../validators';
|
||||||
|
|
||||||
const DEFAULT_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({
|
@Directive({
|
||||||
selector: '[required][ng-control],[required][ng-form-control],[required][ng-model]',
|
selector: '[required][ng-control],[required][ng-form-control],[required][ng-model]',
|
||||||
|
@ -15,7 +15,7 @@ import * as modelModule from './model';
|
|||||||
*
|
*
|
||||||
* @Component({
|
* @Component({
|
||||||
* selector: 'login-comp',
|
* selector: 'login-comp',
|
||||||
* viewBindings: [FormBuilder]
|
* viewProviders: [FormBuilder]
|
||||||
* })
|
* })
|
||||||
* @View({
|
* @View({
|
||||||
* template: `
|
* template: `
|
||||||
|
@ -108,22 +108,18 @@ export class DirectiveResolver {
|
|||||||
var mergedQueries =
|
var mergedQueries =
|
||||||
isPresent(dm.queries) ? StringMapWrapper.merge(dm.queries, queries) : queries;
|
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) {
|
if (dm instanceof ComponentMetadata) {
|
||||||
return new ComponentMetadata({
|
return new ComponentMetadata({
|
||||||
selector: dm.selector,
|
selector: dm.selector,
|
||||||
inputs: mergedInputs,
|
inputs: mergedInputs,
|
||||||
outputs: mergedOutputs,
|
outputs: mergedOutputs,
|
||||||
host: mergedHost,
|
host: mergedHost,
|
||||||
bindings: dm.bindings,
|
|
||||||
exportAs: dm.exportAs,
|
exportAs: dm.exportAs,
|
||||||
moduleId: dm.moduleId,
|
moduleId: dm.moduleId,
|
||||||
queries: mergedQueries,
|
queries: mergedQueries,
|
||||||
changeDetection: dm.changeDetection,
|
changeDetection: dm.changeDetection,
|
||||||
viewBindings: dm.viewBindings
|
providers: dm.providers,
|
||||||
|
viewProviders: dm.viewProviders
|
||||||
});
|
});
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
@ -132,10 +128,10 @@ export class DirectiveResolver {
|
|||||||
inputs: mergedInputs,
|
inputs: mergedInputs,
|
||||||
outputs: mergedOutputs,
|
outputs: mergedOutputs,
|
||||||
host: mergedHost,
|
host: mergedHost,
|
||||||
bindings: dm.bindings,
|
|
||||||
exportAs: dm.exportAs,
|
exportAs: dm.exportAs,
|
||||||
moduleId: dm.moduleId,
|
moduleId: dm.moduleId,
|
||||||
queries: mergedQueries
|
queries: mergedQueries,
|
||||||
|
providers: dm.providers
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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 {Compiler} from './compiler';
|
||||||
import {isType, Type, stringify, isPresent} from 'angular2/src/core/facade/lang';
|
import {isType, Type, stringify, isPresent} from 'angular2/src/core/facade/lang';
|
||||||
import {Promise} from 'angular2/src/core/facade/async';
|
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`
|
* location within the Component View of this Component Instance is specified via `anchorName`
|
||||||
* Template Variable Name.
|
* 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.
|
* Component Instance.
|
||||||
*
|
*
|
||||||
* Returns a promise for the {@link ComponentRef} representing the newly created Component.
|
* 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,
|
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
|
* Creates an instance of a Component and attaches it to the View Container found at the
|
||||||
* `location` specified as {@link ElementRef}.
|
* `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.
|
* Component Instance.
|
||||||
*
|
*
|
||||||
* Returns a promise for the {@link ComponentRef} representing the newly created Component.
|
* 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>
|
* <child-component>Child</child-component>
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
abstract loadNextToLocation(type: Type, location: ElementRef, bindings?: ResolvedBinding[]):
|
abstract loadNextToLocation(type: Type, location: ElementRef, providers?: ResolvedProvider[]):
|
||||||
Promise<ComponentRef>;
|
Promise<ComponentRef>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -283,17 +283,18 @@ export class DynamicComponentLoader_ extends DynamicComponentLoader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
loadIntoLocation(type: Type, hostLocation: ElementRef, anchorName: string,
|
loadIntoLocation(type: Type, hostLocation: ElementRef, anchorName: string,
|
||||||
bindings: ResolvedBinding[] = null): Promise<ComponentRef> {
|
providers: ResolvedProvider[] = null): Promise<ComponentRef> {
|
||||||
return this.loadNextToLocation(
|
return this.loadNextToLocation(
|
||||||
type, this._viewManager.getNamedElementInComponentView(hostLocation, anchorName), bindings);
|
type, this._viewManager.getNamedElementInComponentView(hostLocation, anchorName),
|
||||||
|
providers);
|
||||||
}
|
}
|
||||||
|
|
||||||
loadNextToLocation(type: Type, location: ElementRef,
|
loadNextToLocation(type: Type, location: ElementRef,
|
||||||
bindings: ResolvedBinding[] = null): Promise<ComponentRef> {
|
providers: ResolvedProvider[] = null): Promise<ComponentRef> {
|
||||||
return this._compiler.compileInHost(type).then(hostProtoViewRef => {
|
return this._compiler.compileInHost(type).then(hostProtoViewRef => {
|
||||||
var viewContainer = this._viewManager.getViewContainer(location);
|
var viewContainer = this._viewManager.getViewContainer(location);
|
||||||
var hostViewRef =
|
var hostViewRef =
|
||||||
viewContainer.createHostView(hostProtoViewRef, viewContainer.length, bindings);
|
viewContainer.createHostView(hostProtoViewRef, viewContainer.length, providers);
|
||||||
var newLocation = this._viewManager.getHostElement(hostViewRef);
|
var newLocation = this._viewManager.getHostElement(hostViewRef);
|
||||||
var component = this._viewManager.getComponent(newLocation);
|
var component = this._viewManager.getComponent(newLocation);
|
||||||
|
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
import {isBlank} from 'angular2/src/core/facade/lang';
|
import {isBlank} from 'angular2/src/core/facade/lang';
|
||||||
import {BaseException} from 'angular2/src/core/facade/exceptions';
|
import {BaseException} from 'angular2/src/core/facade/exceptions';
|
||||||
import * as eiModule from './element_injector';
|
import * as eiModule from './element_injector';
|
||||||
import {DirectiveBinding} from './element_injector';
|
import {DirectiveProvider} from './element_injector';
|
||||||
import * as viewModule from './view';
|
import * as viewModule from './view';
|
||||||
|
|
||||||
export class ElementBinder {
|
export class ElementBinder {
|
||||||
constructor(public index: number, public parent: ElementBinder, public distanceToParent: number,
|
constructor(public index: number, public parent: ElementBinder, public distanceToParent: number,
|
||||||
public protoElementInjector: eiModule.ProtoElementInjector,
|
public protoElementInjector: eiModule.ProtoElementInjector,
|
||||||
public componentDirective: DirectiveBinding,
|
public componentDirective: DirectiveProvider,
|
||||||
public nestedProtoView: viewModule.AppProtoView) {
|
public nestedProtoView: viewModule.AppProtoView) {
|
||||||
if (isBlank(index)) {
|
if (isBlank(index)) {
|
||||||
throw new BaseException('null index not allowed.');
|
throw new BaseException('null index not allowed.');
|
||||||
|
@ -13,11 +13,11 @@ import {
|
|||||||
Injector,
|
Injector,
|
||||||
Key,
|
Key,
|
||||||
Dependency,
|
Dependency,
|
||||||
bind,
|
provide,
|
||||||
Binding,
|
Provider,
|
||||||
ResolvedBinding,
|
ResolvedProvider,
|
||||||
NoBindingError,
|
NoProviderError,
|
||||||
AbstractBindingError,
|
AbstractProviderError,
|
||||||
CyclicDependencyError,
|
CyclicDependencyError,
|
||||||
resolveForwardRef
|
resolveForwardRef
|
||||||
} from 'angular2/src/core/di';
|
} from 'angular2/src/core/di';
|
||||||
@ -27,10 +27,10 @@ import {
|
|||||||
Visibility,
|
Visibility,
|
||||||
InjectorInlineStrategy,
|
InjectorInlineStrategy,
|
||||||
InjectorDynamicStrategy,
|
InjectorDynamicStrategy,
|
||||||
BindingWithVisibility,
|
ProviderWithVisibility,
|
||||||
DependencyProvider
|
DependencyProvider
|
||||||
} from 'angular2/src/core/di/injector';
|
} 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';
|
import {AttributeMetadata, QueryMetadata} from '../metadata/di';
|
||||||
|
|
||||||
@ -49,7 +49,7 @@ import {QueryList} from './query_list';
|
|||||||
import {reflector} from 'angular2/src/core/reflection/reflection';
|
import {reflector} from 'angular2/src/core/reflection/reflection';
|
||||||
import {SetterFn} from 'angular2/src/core/reflection/types';
|
import {SetterFn} from 'angular2/src/core/reflection/types';
|
||||||
import {EventConfig} from 'angular2/src/core/linker/event_config';
|
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 {LifecycleHooks} from './interfaces';
|
||||||
import {ViewContainerRef_} from "./view_container_ref";
|
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;
|
public callOnDestroy: boolean;
|
||||||
|
|
||||||
constructor(key: Key, factory: Function, deps: Dependency[], public metadata: DirectiveMetadata,
|
constructor(key: Key, factory: Function, deps: Dependency[], public metadata: DirectiveMetadata,
|
||||||
public bindings: Array<Type | Binding | any[]>,
|
public providers: Array<Type | Provider | any[]>,
|
||||||
public viewBindings: Array<Type | Binding | any[]>) {
|
public viewProviders: Array<Type | Provider | any[]>) {
|
||||||
super(key, [new ResolvedFactory(factory, deps)], false);
|
super(key, [new ResolvedFactory(factory, deps)], false);
|
||||||
this.callOnDestroy = hasLifecycleHook(LifecycleHooks.OnDestroy, key.token);
|
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)) {
|
if (isBlank(meta)) {
|
||||||
meta = new DirectiveMetadata();
|
meta = new DirectiveMetadata();
|
||||||
}
|
}
|
||||||
|
|
||||||
var rb = resolveBinding(binding);
|
var rb = resolveProvider(provider);
|
||||||
var rf = rb.resolvedFactories[0];
|
var rf = rb.resolvedFactories[0];
|
||||||
var deps = rf.dependencies.map(DirectiveDependency.createFrom);
|
var deps = rf.dependencies.map(DirectiveDependency.createFrom);
|
||||||
|
|
||||||
var bindings = isPresent(meta.bindings) ? meta.bindings : [];
|
var providers = isPresent(meta.providers) ? meta.providers : [];
|
||||||
var viewBindigs =
|
var viewBindigs = meta instanceof ComponentMetadata && isPresent(meta.viewProviders) ?
|
||||||
meta instanceof ComponentMetadata && isPresent(meta.viewBindings) ? meta.viewBindings : [];
|
meta.viewProviders :
|
||||||
return new DirectiveBinding(rb.key, rf.factory, deps, meta, bindings, viewBindigs);
|
[];
|
||||||
|
return new DirectiveProvider(rb.key, rf.factory, deps, meta, providers, viewBindigs);
|
||||||
}
|
}
|
||||||
|
|
||||||
static createFromType(type: Type, annotation: DirectiveMetadata): DirectiveBinding {
|
static createFromType(type: Type, annotation: DirectiveMetadata): DirectiveProvider {
|
||||||
var binding = new Binding(type, {toClass: type});
|
var provider = new Provider(type, {toClass: type});
|
||||||
return DirectiveBinding.createFromBinding(binding, annotation);
|
return DirectiveProvider.createFromProvider(provider, annotation);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -200,29 +201,29 @@ export class EventEmitterAccessor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function _createEventEmitterAccessors(bwv: BindingWithVisibility): EventEmitterAccessor[] {
|
function _createEventEmitterAccessors(bwv: ProviderWithVisibility): EventEmitterAccessor[] {
|
||||||
var binding = bwv.binding;
|
var provider = bwv.provider;
|
||||||
if (!(binding instanceof DirectiveBinding)) return [];
|
if (!(provider instanceof DirectiveProvider)) return [];
|
||||||
var db = <DirectiveBinding>binding;
|
var db = <DirectiveProvider>provider;
|
||||||
return db.eventEmitters.map(eventConfig => {
|
return db.eventEmitters.map(eventConfig => {
|
||||||
var parsedEvent = EventConfig.parse(eventConfig);
|
var parsedEvent = EventConfig.parse(eventConfig);
|
||||||
return new EventEmitterAccessor(parsedEvent.eventName, reflector.getter(parsedEvent.fieldName));
|
return new EventEmitterAccessor(parsedEvent.eventName, reflector.getter(parsedEvent.fieldName));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function _createProtoQueryRefs(bindings: BindingWithVisibility[]): ProtoQueryRef[] {
|
function _createProtoQueryRefs(providers: ProviderWithVisibility[]): ProtoQueryRef[] {
|
||||||
var res = [];
|
var res = [];
|
||||||
ListWrapper.forEachWithIndex(bindings, (b, i) => {
|
ListWrapper.forEachWithIndex(providers, (b, i) => {
|
||||||
if (b.binding instanceof DirectiveBinding) {
|
if (b.provider instanceof DirectiveProvider) {
|
||||||
var directiveBinding = <DirectiveBinding>b.binding;
|
var directiveProvider = <DirectiveProvider>b.provider;
|
||||||
// field queries
|
// 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.forEach(q => res.push(new ProtoQueryRef(i, q.setter, q.metadata)));
|
||||||
|
|
||||||
// queries passed into the constructor.
|
// queries passed into the constructor.
|
||||||
// TODO: remove this after constructor queries are no longer supported
|
// TODO: remove this after constructor queries are no longer supported
|
||||||
var deps: DirectiveDependency[] =
|
var deps: DirectiveDependency[] =
|
||||||
<DirectiveDependency[]>directiveBinding.resolvedFactory.dependencies;
|
<DirectiveDependency[]>directiveProvider.resolvedFactory.dependencies;
|
||||||
deps.forEach(d => {
|
deps.forEach(d => {
|
||||||
if (isPresent(d.queryDecorator)) res.push(new ProtoQueryRef(i, null, d.queryDecorator));
|
if (isPresent(d.queryDecorator)) res.push(new ProtoQueryRef(i, null, d.queryDecorator));
|
||||||
});
|
});
|
||||||
@ -238,67 +239,67 @@ export class ProtoElementInjector {
|
|||||||
protoQueryRefs: ProtoQueryRef[];
|
protoQueryRefs: ProtoQueryRef[];
|
||||||
protoInjector: ProtoInjector;
|
protoInjector: ProtoInjector;
|
||||||
|
|
||||||
static create(parent: ProtoElementInjector, index: number, bindings: DirectiveBinding[],
|
static create(parent: ProtoElementInjector, index: number, providers: DirectiveProvider[],
|
||||||
firstBindingIsComponent: boolean, distanceToParent: number,
|
firstProviderIsComponent: boolean, distanceToParent: number,
|
||||||
directiveVariableBindings: Map<string, number>): ProtoElementInjector {
|
directiveVariableBindings: Map<string, number>): ProtoElementInjector {
|
||||||
var bd = [];
|
var bd = [];
|
||||||
|
|
||||||
ProtoElementInjector._createDirectiveBindingWithVisibility(bindings, bd,
|
ProtoElementInjector._createDirectiveProviderWithVisibility(providers, bd,
|
||||||
firstBindingIsComponent);
|
firstProviderIsComponent);
|
||||||
if (firstBindingIsComponent) {
|
if (firstProviderIsComponent) {
|
||||||
ProtoElementInjector._createViewBindingsWithVisibility(bindings, bd);
|
ProtoElementInjector._createViewProvidersWithVisibility(providers, bd);
|
||||||
}
|
}
|
||||||
|
|
||||||
ProtoElementInjector._createBindingsWithVisibility(bindings, bd);
|
ProtoElementInjector._createProvidersWithVisibility(providers, bd);
|
||||||
return new ProtoElementInjector(parent, index, bd, distanceToParent, firstBindingIsComponent,
|
return new ProtoElementInjector(parent, index, bd, distanceToParent, firstProviderIsComponent,
|
||||||
directiveVariableBindings);
|
directiveVariableBindings);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static _createDirectiveBindingWithVisibility(dirBindings: DirectiveBinding[],
|
private static _createDirectiveProviderWithVisibility(dirProviders: DirectiveProvider[],
|
||||||
bd: BindingWithVisibility[],
|
bd: ProviderWithVisibility[],
|
||||||
firstBindingIsComponent: boolean) {
|
firstProviderIsComponent: boolean) {
|
||||||
dirBindings.forEach(dirBinding => {
|
dirProviders.forEach(dirProvider => {
|
||||||
bd.push(ProtoElementInjector._createBindingWithVisibility(firstBindingIsComponent, dirBinding,
|
bd.push(ProtoElementInjector._createProviderWithVisibility(
|
||||||
dirBindings, dirBinding));
|
firstProviderIsComponent, dirProvider, dirProviders, dirProvider));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private static _createBindingsWithVisibility(dirBindings: DirectiveBinding[],
|
private static _createProvidersWithVisibility(dirProviders: DirectiveProvider[],
|
||||||
bd: BindingWithVisibility[]) {
|
bd: ProviderWithVisibility[]) {
|
||||||
var bindingsFromAllDirectives = [];
|
var providersFromAllDirectives = [];
|
||||||
dirBindings.forEach(dirBinding => {
|
dirProviders.forEach(dirProvider => {
|
||||||
bindingsFromAllDirectives =
|
providersFromAllDirectives =
|
||||||
ListWrapper.concat(bindingsFromAllDirectives, dirBinding.bindings);
|
ListWrapper.concat(providersFromAllDirectives, dirProvider.providers);
|
||||||
});
|
});
|
||||||
|
|
||||||
var resolved = Injector.resolve(bindingsFromAllDirectives);
|
var resolved = Injector.resolve(providersFromAllDirectives);
|
||||||
resolved.forEach(b => bd.push(new BindingWithVisibility(b, Visibility.Public)));
|
resolved.forEach(b => bd.push(new ProviderWithVisibility(b, Visibility.Public)));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static _createBindingWithVisibility(firstBindingIsComponent: boolean,
|
private static _createProviderWithVisibility(firstProviderIsComponent: boolean,
|
||||||
dirBinding: DirectiveBinding,
|
dirProvider: DirectiveProvider,
|
||||||
dirBindings: DirectiveBinding[],
|
dirProviders: DirectiveProvider[],
|
||||||
binding: ResolvedBinding) {
|
provider: ResolvedProvider) {
|
||||||
var isComponent = firstBindingIsComponent && dirBindings[0] === dirBinding;
|
var isComponent = firstProviderIsComponent && dirProviders[0] === dirProvider;
|
||||||
return new BindingWithVisibility(binding,
|
return new ProviderWithVisibility(
|
||||||
isComponent ? Visibility.PublicAndPrivate : Visibility.Public);
|
provider, isComponent ? Visibility.PublicAndPrivate : Visibility.Public);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static _createViewBindingsWithVisibility(dirBindings: DirectiveBinding[],
|
private static _createViewProvidersWithVisibility(dirProviders: DirectiveProvider[],
|
||||||
bd: BindingWithVisibility[]) {
|
bd: ProviderWithVisibility[]) {
|
||||||
var resolvedViewBindings = Injector.resolve(dirBindings[0].viewBindings);
|
var resolvedViewProviders = Injector.resolve(dirProviders[0].viewProviders);
|
||||||
resolvedViewBindings.forEach(b => bd.push(new BindingWithVisibility(b, Visibility.Private)));
|
resolvedViewProviders.forEach(b => bd.push(new ProviderWithVisibility(b, Visibility.Private)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @internal */
|
/** @internal */
|
||||||
public _firstBindingIsComponent: boolean;
|
public _firstProviderIsComponent: boolean;
|
||||||
|
|
||||||
|
|
||||||
constructor(public parent: ProtoElementInjector, public index: number,
|
constructor(public parent: ProtoElementInjector, public index: number,
|
||||||
bwv: BindingWithVisibility[], public distanceToParent: number,
|
bwv: ProviderWithVisibility[], public distanceToParent: number,
|
||||||
_firstBindingIsComponent: boolean,
|
_firstProviderIsComponent: boolean,
|
||||||
public directiveVariableBindings: Map<string, number>) {
|
public directiveVariableBindings: Map<string, number>) {
|
||||||
this._firstBindingIsComponent = _firstBindingIsComponent;
|
this._firstProviderIsComponent = _firstProviderIsComponent;
|
||||||
var length = bwv.length;
|
var length = bwv.length;
|
||||||
this.protoInjector = new ProtoInjector(bwv);
|
this.protoInjector = new ProtoInjector(bwv);
|
||||||
this.eventEmitterAccessors = ListWrapper.createFixedSize(length);
|
this.eventEmitterAccessors = ListWrapper.createFixedSize(length);
|
||||||
@ -316,7 +317,7 @@ export class ProtoElementInjector {
|
|||||||
|
|
||||||
get hasBindings(): boolean { return this.eventEmitterAccessors.length > 0; }
|
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 {
|
class _Context {
|
||||||
@ -456,12 +457,12 @@ export class ElementInjector extends TreeNode<ElementInjector> implements Depend
|
|||||||
|
|
||||||
isComponentKey(key: Key): boolean { return this._strategy.isComponentKey(key); }
|
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;
|
var key: Key = dep.key;
|
||||||
|
|
||||||
if (binding instanceof DirectiveBinding) {
|
if (provider instanceof DirectiveProvider) {
|
||||||
var dirDep = <DirectiveDependency>dep;
|
var dirDep = <DirectiveDependency>dep;
|
||||||
var dirBin = binding;
|
var dirProvider = provider;
|
||||||
var staticKeys = StaticKeys.instance();
|
var staticKeys = StaticKeys.instance();
|
||||||
|
|
||||||
|
|
||||||
@ -475,7 +476,7 @@ export class ElementInjector extends TreeNode<ElementInjector> implements Depend
|
|||||||
if (dirDep.key.id === StaticKeys.instance().changeDetectorRefId) {
|
if (dirDep.key.id === StaticKeys.instance().changeDetectorRefId) {
|
||||||
// We provide the component's view change detector to components and
|
// We provide the component's view change detector to components and
|
||||||
// the surrounding component's change detector to directives.
|
// the surrounding component's change detector to directives.
|
||||||
if (dirBin.metadata instanceof ComponentMetadata) {
|
if (dirProvider.metadata instanceof ComponentMetadata) {
|
||||||
var componentView = this._preBuiltObjects.view.getNestedView(
|
var componentView = this._preBuiltObjects.view.getNestedView(
|
||||||
this._preBuiltObjects.elementRef.boundElementIndex);
|
this._preBuiltObjects.elementRef.boundElementIndex);
|
||||||
return componentView.changeDetector.ref;
|
return componentView.changeDetector.ref;
|
||||||
@ -498,12 +499,12 @@ export class ElementInjector extends TreeNode<ElementInjector> implements Depend
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new NoBindingError(null, dirDep.key);
|
throw new NoProviderError(null, dirDep.key);
|
||||||
}
|
}
|
||||||
return this._preBuiltObjects.templateRef;
|
return this._preBuiltObjects.templateRef;
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if (binding instanceof PipeBinding) {
|
} else if (provider instanceof PipeProvider) {
|
||||||
if (dep.key.id === StaticKeys.instance().changeDetectorRefId) {
|
if (dep.key.id === StaticKeys.instance().changeDetectorRefId) {
|
||||||
var componentView = this._preBuiltObjects.view.getNestedView(
|
var componentView = this._preBuiltObjects.view.getNestedView(
|
||||||
this._preBuiltObjects.elementRef.boundElementIndex);
|
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.
|
* In such a case, inlining fields is beneficial for performances.
|
||||||
*/
|
*/
|
||||||
class ElementInjectorInlineStrategy implements _ElementInjectorStrategy {
|
class ElementInjectorInlineStrategy implements _ElementInjectorStrategy {
|
||||||
@ -764,26 +765,26 @@ class ElementInjectorInlineStrategy implements _ElementInjectorStrategy {
|
|||||||
var p = i.protoStrategy;
|
var p = i.protoStrategy;
|
||||||
i.resetConstructionCounter();
|
i.resetConstructionCounter();
|
||||||
|
|
||||||
if (p.binding0 instanceof DirectiveBinding && isPresent(p.keyId0) && i.obj0 === UNDEFINED)
|
if (p.provider0 instanceof DirectiveProvider && isPresent(p.keyId0) && i.obj0 === UNDEFINED)
|
||||||
i.obj0 = i.instantiateBinding(p.binding0, p.visibility0);
|
i.obj0 = i.instantiateProvider(p.provider0, p.visibility0);
|
||||||
if (p.binding1 instanceof DirectiveBinding && isPresent(p.keyId1) && i.obj1 === UNDEFINED)
|
if (p.provider1 instanceof DirectiveProvider && isPresent(p.keyId1) && i.obj1 === UNDEFINED)
|
||||||
i.obj1 = i.instantiateBinding(p.binding1, p.visibility1);
|
i.obj1 = i.instantiateProvider(p.provider1, p.visibility1);
|
||||||
if (p.binding2 instanceof DirectiveBinding && isPresent(p.keyId2) && i.obj2 === UNDEFINED)
|
if (p.provider2 instanceof DirectiveProvider && isPresent(p.keyId2) && i.obj2 === UNDEFINED)
|
||||||
i.obj2 = i.instantiateBinding(p.binding2, p.visibility2);
|
i.obj2 = i.instantiateProvider(p.provider2, p.visibility2);
|
||||||
if (p.binding3 instanceof DirectiveBinding && isPresent(p.keyId3) && i.obj3 === UNDEFINED)
|
if (p.provider3 instanceof DirectiveProvider && isPresent(p.keyId3) && i.obj3 === UNDEFINED)
|
||||||
i.obj3 = i.instantiateBinding(p.binding3, p.visibility3);
|
i.obj3 = i.instantiateProvider(p.provider3, p.visibility3);
|
||||||
if (p.binding4 instanceof DirectiveBinding && isPresent(p.keyId4) && i.obj4 === UNDEFINED)
|
if (p.provider4 instanceof DirectiveProvider && isPresent(p.keyId4) && i.obj4 === UNDEFINED)
|
||||||
i.obj4 = i.instantiateBinding(p.binding4, p.visibility4);
|
i.obj4 = i.instantiateProvider(p.provider4, p.visibility4);
|
||||||
if (p.binding5 instanceof DirectiveBinding && isPresent(p.keyId5) && i.obj5 === UNDEFINED)
|
if (p.provider5 instanceof DirectiveProvider && isPresent(p.keyId5) && i.obj5 === UNDEFINED)
|
||||||
i.obj5 = i.instantiateBinding(p.binding5, p.visibility5);
|
i.obj5 = i.instantiateProvider(p.provider5, p.visibility5);
|
||||||
if (p.binding6 instanceof DirectiveBinding && isPresent(p.keyId6) && i.obj6 === UNDEFINED)
|
if (p.provider6 instanceof DirectiveProvider && isPresent(p.keyId6) && i.obj6 === UNDEFINED)
|
||||||
i.obj6 = i.instantiateBinding(p.binding6, p.visibility6);
|
i.obj6 = i.instantiateProvider(p.provider6, p.visibility6);
|
||||||
if (p.binding7 instanceof DirectiveBinding && isPresent(p.keyId7) && i.obj7 === UNDEFINED)
|
if (p.provider7 instanceof DirectiveProvider && isPresent(p.keyId7) && i.obj7 === UNDEFINED)
|
||||||
i.obj7 = i.instantiateBinding(p.binding7, p.visibility7);
|
i.obj7 = i.instantiateProvider(p.provider7, p.visibility7);
|
||||||
if (p.binding8 instanceof DirectiveBinding && isPresent(p.keyId8) && i.obj8 === UNDEFINED)
|
if (p.provider8 instanceof DirectiveProvider && isPresent(p.keyId8) && i.obj8 === UNDEFINED)
|
||||||
i.obj8 = i.instantiateBinding(p.binding8, p.visibility8);
|
i.obj8 = i.instantiateProvider(p.provider8, p.visibility8);
|
||||||
if (p.binding9 instanceof DirectiveBinding && isPresent(p.keyId9) && i.obj9 === UNDEFINED)
|
if (p.provider9 instanceof DirectiveProvider && isPresent(p.keyId9) && i.obj9 === UNDEFINED)
|
||||||
i.obj9 = i.instantiateBinding(p.binding9, p.visibility9);
|
i.obj9 = i.instantiateProvider(p.provider9, p.visibility9);
|
||||||
}
|
}
|
||||||
|
|
||||||
dehydrate() {
|
dehydrate() {
|
||||||
@ -805,34 +806,44 @@ class ElementInjectorInlineStrategy implements _ElementInjectorStrategy {
|
|||||||
var i = this.injectorStrategy;
|
var i = this.injectorStrategy;
|
||||||
var p = i.protoStrategy;
|
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();
|
i.obj0.onDestroy();
|
||||||
}
|
}
|
||||||
if (p.binding1 instanceof DirectiveBinding && (<DirectiveBinding>p.binding1).callOnDestroy) {
|
if (p.provider1 instanceof DirectiveProvider &&
|
||||||
|
(<DirectiveProvider>p.provider1).callOnDestroy) {
|
||||||
i.obj1.onDestroy();
|
i.obj1.onDestroy();
|
||||||
}
|
}
|
||||||
if (p.binding2 instanceof DirectiveBinding && (<DirectiveBinding>p.binding2).callOnDestroy) {
|
if (p.provider2 instanceof DirectiveProvider &&
|
||||||
|
(<DirectiveProvider>p.provider2).callOnDestroy) {
|
||||||
i.obj2.onDestroy();
|
i.obj2.onDestroy();
|
||||||
}
|
}
|
||||||
if (p.binding3 instanceof DirectiveBinding && (<DirectiveBinding>p.binding3).callOnDestroy) {
|
if (p.provider3 instanceof DirectiveProvider &&
|
||||||
|
(<DirectiveProvider>p.provider3).callOnDestroy) {
|
||||||
i.obj3.onDestroy();
|
i.obj3.onDestroy();
|
||||||
}
|
}
|
||||||
if (p.binding4 instanceof DirectiveBinding && (<DirectiveBinding>p.binding4).callOnDestroy) {
|
if (p.provider4 instanceof DirectiveProvider &&
|
||||||
|
(<DirectiveProvider>p.provider4).callOnDestroy) {
|
||||||
i.obj4.onDestroy();
|
i.obj4.onDestroy();
|
||||||
}
|
}
|
||||||
if (p.binding5 instanceof DirectiveBinding && (<DirectiveBinding>p.binding5).callOnDestroy) {
|
if (p.provider5 instanceof DirectiveProvider &&
|
||||||
|
(<DirectiveProvider>p.provider5).callOnDestroy) {
|
||||||
i.obj5.onDestroy();
|
i.obj5.onDestroy();
|
||||||
}
|
}
|
||||||
if (p.binding6 instanceof DirectiveBinding && (<DirectiveBinding>p.binding6).callOnDestroy) {
|
if (p.provider6 instanceof DirectiveProvider &&
|
||||||
|
(<DirectiveProvider>p.provider6).callOnDestroy) {
|
||||||
i.obj6.onDestroy();
|
i.obj6.onDestroy();
|
||||||
}
|
}
|
||||||
if (p.binding7 instanceof DirectiveBinding && (<DirectiveBinding>p.binding7).callOnDestroy) {
|
if (p.provider7 instanceof DirectiveProvider &&
|
||||||
|
(<DirectiveProvider>p.provider7).callOnDestroy) {
|
||||||
i.obj7.onDestroy();
|
i.obj7.onDestroy();
|
||||||
}
|
}
|
||||||
if (p.binding8 instanceof DirectiveBinding && (<DirectiveBinding>p.binding8).callOnDestroy) {
|
if (p.provider8 instanceof DirectiveProvider &&
|
||||||
|
(<DirectiveProvider>p.provider8).callOnDestroy) {
|
||||||
i.obj8.onDestroy();
|
i.obj8.onDestroy();
|
||||||
}
|
}
|
||||||
if (p.binding9 instanceof DirectiveBinding && (<DirectiveBinding>p.binding9).callOnDestroy) {
|
if (p.provider9 instanceof DirectiveProvider &&
|
||||||
|
(<DirectiveProvider>p.provider9).callOnDestroy) {
|
||||||
i.obj9.onDestroy();
|
i.obj9.onDestroy();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -840,7 +851,7 @@ class ElementInjectorInlineStrategy implements _ElementInjectorStrategy {
|
|||||||
getComponent(): any { return this.injectorStrategy.obj0; }
|
getComponent(): any { return this.injectorStrategy.obj0; }
|
||||||
|
|
||||||
isComponentKey(key: Key): boolean {
|
isComponentKey(key: Key): boolean {
|
||||||
return this._ei._proto._firstBindingIsComponent && isPresent(key) &&
|
return this._ei._proto._firstProviderIsComponent && isPresent(key) &&
|
||||||
key.id === this.injectorStrategy.protoStrategy.keyId0;
|
key.id === this.injectorStrategy.protoStrategy.keyId0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -848,51 +859,51 @@ class ElementInjectorInlineStrategy implements _ElementInjectorStrategy {
|
|||||||
var i = this.injectorStrategy;
|
var i = this.injectorStrategy;
|
||||||
var p = i.protoStrategy;
|
var p = i.protoStrategy;
|
||||||
|
|
||||||
if (isPresent(p.binding0) && p.binding0.key.token === query.selector) {
|
if (isPresent(p.provider0) && p.provider0.key.token === query.selector) {
|
||||||
if (i.obj0 === UNDEFINED) i.obj0 = i.instantiateBinding(p.binding0, p.visibility0);
|
if (i.obj0 === UNDEFINED) i.obj0 = i.instantiateProvider(p.provider0, p.visibility0);
|
||||||
list.push(i.obj0);
|
list.push(i.obj0);
|
||||||
}
|
}
|
||||||
if (isPresent(p.binding1) && p.binding1.key.token === query.selector) {
|
if (isPresent(p.provider1) && p.provider1.key.token === query.selector) {
|
||||||
if (i.obj1 === UNDEFINED) i.obj1 = i.instantiateBinding(p.binding1, p.visibility1);
|
if (i.obj1 === UNDEFINED) i.obj1 = i.instantiateProvider(p.provider1, p.visibility1);
|
||||||
list.push(i.obj1);
|
list.push(i.obj1);
|
||||||
}
|
}
|
||||||
if (isPresent(p.binding2) && p.binding2.key.token === query.selector) {
|
if (isPresent(p.provider2) && p.provider2.key.token === query.selector) {
|
||||||
if (i.obj2 === UNDEFINED) i.obj2 = i.instantiateBinding(p.binding2, p.visibility2);
|
if (i.obj2 === UNDEFINED) i.obj2 = i.instantiateProvider(p.provider2, p.visibility2);
|
||||||
list.push(i.obj2);
|
list.push(i.obj2);
|
||||||
}
|
}
|
||||||
if (isPresent(p.binding3) && p.binding3.key.token === query.selector) {
|
if (isPresent(p.provider3) && p.provider3.key.token === query.selector) {
|
||||||
if (i.obj3 === UNDEFINED) i.obj3 = i.instantiateBinding(p.binding3, p.visibility3);
|
if (i.obj3 === UNDEFINED) i.obj3 = i.instantiateProvider(p.provider3, p.visibility3);
|
||||||
list.push(i.obj3);
|
list.push(i.obj3);
|
||||||
}
|
}
|
||||||
if (isPresent(p.binding4) && p.binding4.key.token === query.selector) {
|
if (isPresent(p.provider4) && p.provider4.key.token === query.selector) {
|
||||||
if (i.obj4 === UNDEFINED) i.obj4 = i.instantiateBinding(p.binding4, p.visibility4);
|
if (i.obj4 === UNDEFINED) i.obj4 = i.instantiateProvider(p.provider4, p.visibility4);
|
||||||
list.push(i.obj4);
|
list.push(i.obj4);
|
||||||
}
|
}
|
||||||
if (isPresent(p.binding5) && p.binding5.key.token === query.selector) {
|
if (isPresent(p.provider5) && p.provider5.key.token === query.selector) {
|
||||||
if (i.obj5 === UNDEFINED) i.obj5 = i.instantiateBinding(p.binding5, p.visibility5);
|
if (i.obj5 === UNDEFINED) i.obj5 = i.instantiateProvider(p.provider5, p.visibility5);
|
||||||
list.push(i.obj5);
|
list.push(i.obj5);
|
||||||
}
|
}
|
||||||
if (isPresent(p.binding6) && p.binding6.key.token === query.selector) {
|
if (isPresent(p.provider6) && p.provider6.key.token === query.selector) {
|
||||||
if (i.obj6 === UNDEFINED) i.obj6 = i.instantiateBinding(p.binding6, p.visibility6);
|
if (i.obj6 === UNDEFINED) i.obj6 = i.instantiateProvider(p.provider6, p.visibility6);
|
||||||
list.push(i.obj6);
|
list.push(i.obj6);
|
||||||
}
|
}
|
||||||
if (isPresent(p.binding7) && p.binding7.key.token === query.selector) {
|
if (isPresent(p.provider7) && p.provider7.key.token === query.selector) {
|
||||||
if (i.obj7 === UNDEFINED) i.obj7 = i.instantiateBinding(p.binding7, p.visibility7);
|
if (i.obj7 === UNDEFINED) i.obj7 = i.instantiateProvider(p.provider7, p.visibility7);
|
||||||
list.push(i.obj7);
|
list.push(i.obj7);
|
||||||
}
|
}
|
||||||
if (isPresent(p.binding8) && p.binding8.key.token === query.selector) {
|
if (isPresent(p.provider8) && p.provider8.key.token === query.selector) {
|
||||||
if (i.obj8 === UNDEFINED) i.obj8 = i.instantiateBinding(p.binding8, p.visibility8);
|
if (i.obj8 === UNDEFINED) i.obj8 = i.instantiateProvider(p.provider8, p.visibility8);
|
||||||
list.push(i.obj8);
|
list.push(i.obj8);
|
||||||
}
|
}
|
||||||
if (isPresent(p.binding9) && p.binding9.key.token === query.selector) {
|
if (isPresent(p.provider9) && p.provider9.key.token === query.selector) {
|
||||||
if (i.obj9 === UNDEFINED) i.obj9 = i.instantiateBinding(p.binding9, p.visibility9);
|
if (i.obj9 === UNDEFINED) i.obj9 = i.instantiateProvider(p.provider9, p.visibility9);
|
||||||
list.push(i.obj9);
|
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.
|
* In such a case, inlining fields is beneficial for performances.
|
||||||
*/
|
*/
|
||||||
class ElementInjectorDynamicStrategy implements _ElementInjectorStrategy {
|
class ElementInjectorDynamicStrategy implements _ElementInjectorStrategy {
|
||||||
@ -904,9 +915,9 @@ class ElementInjectorDynamicStrategy implements _ElementInjectorStrategy {
|
|||||||
inj.resetConstructionCounter();
|
inj.resetConstructionCounter();
|
||||||
|
|
||||||
for (var i = 0; i < p.keyIds.length; i++) {
|
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] === 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 ist = this.injectorStrategy;
|
||||||
var p = ist.protoStrategy;
|
var p = ist.protoStrategy;
|
||||||
|
|
||||||
for (var i = 0; i < p.bindings.length; i++) {
|
for (var i = 0; i < p.providers.length; i++) {
|
||||||
if (p.bindings[i] instanceof DirectiveBinding &&
|
if (p.providers[i] instanceof DirectiveProvider &&
|
||||||
(<DirectiveBinding>p.bindings[i]).callOnDestroy) {
|
(<DirectiveProvider>p.providers[i]).callOnDestroy) {
|
||||||
ist.objs[i].onDestroy();
|
ist.objs[i].onDestroy();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -932,17 +943,17 @@ class ElementInjectorDynamicStrategy implements _ElementInjectorStrategy {
|
|||||||
|
|
||||||
isComponentKey(key: Key): boolean {
|
isComponentKey(key: Key): boolean {
|
||||||
var p = this.injectorStrategy.protoStrategy;
|
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 {
|
addDirectivesMatchingQuery(query: QueryMetadata, list: any[]): void {
|
||||||
var ist = this.injectorStrategy;
|
var ist = this.injectorStrategy;
|
||||||
var p = ist.protoStrategy;
|
var p = ist.protoStrategy;
|
||||||
|
|
||||||
for (var i = 0; i < p.bindings.length; i++) {
|
for (var i = 0; i < p.providers.length; i++) {
|
||||||
if (p.bindings[i].key.token === query.selector) {
|
if (p.providers[i].key.token === query.selector) {
|
||||||
if (ist.objs[i] === UNDEFINED) {
|
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]);
|
list.push(ist.objs[i]);
|
||||||
}
|
}
|
||||||
@ -1025,7 +1036,7 @@ export class QueryRef {
|
|||||||
|
|
||||||
private _visitInjector(inj: ElementInjector, aggregator: any[]) {
|
private _visitInjector(inj: ElementInjector, aggregator: any[]) {
|
||||||
if (this.protoQueryRef.query.isVarBindingQuery) {
|
if (this.protoQueryRef.query.isVarBindingQuery) {
|
||||||
this._aggregateVariableBindings(inj, aggregator);
|
this._aggregateVariableBinding(inj, aggregator);
|
||||||
} else {
|
} else {
|
||||||
this._aggregateDirective(inj, aggregator);
|
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;
|
var vb = this.protoQueryRef.query.varBindings;
|
||||||
for (var i = 0; i < vb.length; ++i) {
|
for (var i = 0; i < vb.length; ++i) {
|
||||||
if (inj.hasVariableBinding(vb[i])) {
|
if (inj.hasVariableBinding(vb[i])) {
|
||||||
|
@ -3,14 +3,14 @@ import {isPresent, isBlank, Type, isArray, isNumber} from 'angular2/src/core/fac
|
|||||||
|
|
||||||
import {RenderProtoViewRef} from 'angular2/src/core/render/api';
|
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 {ProtoPipes} from '../pipes/pipes';
|
||||||
|
|
||||||
import {AppProtoView, AppProtoViewMergeInfo, ViewType} from './view';
|
import {AppProtoView, AppProtoViewMergeInfo, ViewType} from './view';
|
||||||
import {ElementBinder} from './element_binder';
|
import {ElementBinder} from './element_binder';
|
||||||
import {ProtoElementInjector, DirectiveBinding} from './element_injector';
|
import {ProtoElementInjector, DirectiveProvider} from './element_injector';
|
||||||
import {DirectiveResolver} from './directive_resolver';
|
import {DirectiveResolver} from './directive_resolver';
|
||||||
import {ViewResolver} from './view_resolver';
|
import {ViewResolver} from './view_resolver';
|
||||||
import {PipeResolver} from './pipe_resolver';
|
import {PipeResolver} from './pipe_resolver';
|
||||||
@ -55,7 +55,7 @@ export class ProtoViewFactory {
|
|||||||
var result = this._cache.get(compiledTemplate.id);
|
var result = this._cache.get(compiledTemplate.id);
|
||||||
if (isBlank(result)) {
|
if (isBlank(result)) {
|
||||||
var templateData = compiledTemplate.getData(this._appId);
|
var templateData = compiledTemplate.getData(this._appId);
|
||||||
var emptyMap: {[key: string]: PipeBinding} = {};
|
var emptyMap: {[key: string]: PipeProvider} = {};
|
||||||
result = new AppProtoView(templateData.commands, ViewType.HOST, true,
|
result = new AppProtoView(templateData.commands, ViewType.HOST, true,
|
||||||
templateData.changeDetectorFactory, null, new ProtoPipes(emptyMap));
|
templateData.changeDetectorFactory, null, new ProtoPipes(emptyMap));
|
||||||
this._cache.set(compiledTemplate.id, result);
|
this._cache.set(compiledTemplate.id, result);
|
||||||
@ -76,7 +76,7 @@ export class ProtoViewFactory {
|
|||||||
|
|
||||||
nestedProtoView = new AppProtoView(compiledTemplateData.commands, ViewType.COMPONENT, true,
|
nestedProtoView = new AppProtoView(compiledTemplateData.commands, ViewType.COMPONENT, true,
|
||||||
compiledTemplateData.changeDetectorFactory, null,
|
compiledTemplateData.changeDetectorFactory, null,
|
||||||
ProtoPipes.fromBindings(boundPipes));
|
ProtoPipes.fromProviders(boundPipes));
|
||||||
// Note: The cache is updated before recursing
|
// Note: The cache is updated before recursing
|
||||||
// to be able to resolve cycles
|
// to be able to resolve cycles
|
||||||
this._cache.set(cmd.template.id, nestedProtoView);
|
this._cache.set(cmd.template.id, nestedProtoView);
|
||||||
@ -112,9 +112,9 @@ export class ProtoViewFactory {
|
|||||||
initializer.variableLocations);
|
initializer.variableLocations);
|
||||||
}
|
}
|
||||||
|
|
||||||
private _bindPipe(typeOrBinding): PipeBinding {
|
private _bindPipe(typeOrProvider): PipeProvider {
|
||||||
let meta = this._pipeResolver.resolve(typeOrBinding);
|
let meta = this._pipeResolver.resolve(typeOrProvider);
|
||||||
return PipeBinding.createFromType(typeOrBinding, meta);
|
return PipeProvider.createFromType(typeOrProvider, meta);
|
||||||
}
|
}
|
||||||
|
|
||||||
private _flattenPipes(view: ViewMetadata): any[] {
|
private _flattenPipes(view: ViewMetadata): any[] {
|
||||||
@ -245,12 +245,12 @@ function _createElementBinder(directiveResolver: DirectiveResolver, nestedProtoV
|
|||||||
if (isBlank(parentProtoElementInjector)) {
|
if (isBlank(parentProtoElementInjector)) {
|
||||||
distanceToParentPei = -1;
|
distanceToParentPei = -1;
|
||||||
}
|
}
|
||||||
var componentDirectiveBinding: DirectiveBinding = null;
|
var componentDirectiveProvider: DirectiveProvider = null;
|
||||||
var isEmbeddedTemplate = false;
|
var isEmbeddedTemplate = false;
|
||||||
var directiveBindings: DirectiveBinding[] =
|
var directiveProviders: DirectiveProvider[] =
|
||||||
beginElementCmd.directives.map(type => bindDirective(directiveResolver, type));
|
beginElementCmd.directives.map(type => provideDirective(directiveResolver, type));
|
||||||
if (beginElementCmd instanceof BeginComponentCmd) {
|
if (beginElementCmd instanceof BeginComponentCmd) {
|
||||||
componentDirectiveBinding = directiveBindings[0];
|
componentDirectiveProvider = directiveProviders[0];
|
||||||
} else if (beginElementCmd instanceof EmbeddedTemplateCmd) {
|
} else if (beginElementCmd instanceof EmbeddedTemplateCmd) {
|
||||||
isEmbeddedTemplate = true;
|
isEmbeddedTemplate = true;
|
||||||
}
|
}
|
||||||
@ -262,29 +262,29 @@ function _createElementBinder(directiveResolver: DirectiveResolver, nestedProtoV
|
|||||||
// so that, when hydrating, $implicit can be set to the element.
|
// so that, when hydrating, $implicit can be set to the element.
|
||||||
// - <template> elements need their own ElementInjector so that we can query their TemplateRef
|
// - <template> elements need their own ElementInjector so that we can query their TemplateRef
|
||||||
var hasVariables = beginElementCmd.variableNameAndValues.length > 0;
|
var hasVariables = beginElementCmd.variableNameAndValues.length > 0;
|
||||||
if (directiveBindings.length > 0 || hasVariables || isEmbeddedTemplate) {
|
if (directiveProviders.length > 0 || hasVariables || isEmbeddedTemplate) {
|
||||||
var directiveVariableBindings = new Map<string, number>();
|
var directiveVariableBindings = new Map<string, number>();
|
||||||
if (!isEmbeddedTemplate) {
|
if (!isEmbeddedTemplate) {
|
||||||
directiveVariableBindings =
|
directiveVariableBindings = createDirectiveVariableBindings(
|
||||||
createDirectiveVariableBindings(beginElementCmd.variableNameAndValues, directiveBindings);
|
beginElementCmd.variableNameAndValues, directiveProviders);
|
||||||
}
|
}
|
||||||
protoElementInjector = ProtoElementInjector.create(
|
protoElementInjector = ProtoElementInjector.create(
|
||||||
parentProtoElementInjector, boundElementIndex, directiveBindings,
|
parentProtoElementInjector, boundElementIndex, directiveProviders,
|
||||||
isPresent(componentDirectiveBinding), distanceToParentPei, directiveVariableBindings);
|
isPresent(componentDirectiveProvider), distanceToParentPei, directiveVariableBindings);
|
||||||
protoElementInjector.attributes = arrayToMap(beginElementCmd.attrNameAndValues, false);
|
protoElementInjector.attributes = arrayToMap(beginElementCmd.attrNameAndValues, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
return new ElementBinder(boundElementIndex, parentElementBinder, distanceToParentBinder,
|
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);
|
let annotation = directiveResolver.resolve(type);
|
||||||
return DirectiveBinding.createFromType(type, annotation);
|
return DirectiveProvider.createFromType(type, annotation);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createDirectiveVariableBindings(variableNameAndValues: Array<string | number>,
|
export function createDirectiveVariableBindings(variableNameAndValues: Array<string | number>,
|
||||||
directiveBindings: DirectiveBinding[]):
|
directiveProviders: DirectiveProvider[]):
|
||||||
Map<string, number> {
|
Map<string, number> {
|
||||||
var directiveVariableBindings = new Map<string, number>();
|
var directiveVariableBindings = new Map<string, number>();
|
||||||
for (var i = 0; i < variableNameAndValues.length; i += 2) {
|
for (var i = 0; i < variableNameAndValues.length; i += 2) {
|
||||||
@ -313,7 +313,7 @@ function arrayToMap(arr: string[], inverse: boolean): Map<string, string> {
|
|||||||
return result;
|
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++) {
|
for (var i = 0; i < tree.length; i++) {
|
||||||
var item = resolveForwardRef(tree[i]);
|
var item = resolveForwardRef(tree[i]);
|
||||||
if (isArray(item)) {
|
if (isArray(item)) {
|
||||||
|
@ -21,7 +21,7 @@ import {
|
|||||||
ProtoElementInjector,
|
ProtoElementInjector,
|
||||||
ElementInjector,
|
ElementInjector,
|
||||||
PreBuiltObjects,
|
PreBuiltObjects,
|
||||||
DirectiveBinding
|
DirectiveProvider
|
||||||
} from './element_injector';
|
} from './element_injector';
|
||||||
import {ElementBinder} from './element_binder';
|
import {ElementBinder} from './element_binder';
|
||||||
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
|
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import {ListWrapper} from 'angular2/src/core/facade/collection';
|
import {ListWrapper} from 'angular2/src/core/facade/collection';
|
||||||
import {unimplemented} from 'angular2/src/core/facade/exceptions';
|
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 {isPresent, isBlank} from 'angular2/src/core/facade/lang';
|
||||||
|
|
||||||
import * as avmModule from './view_manager';
|
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.
|
* 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.
|
* that will be created for the Host View.
|
||||||
*
|
*
|
||||||
* Returns the {@link HostViewRef} of the Host View created for the newly instantiated Component.
|
* Returns the {@link HostViewRef} of the Host View created for the newly instantiated Component.
|
||||||
*/
|
*/
|
||||||
abstract createHostView(protoViewRef?: ProtoViewRef, index?: number,
|
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`.
|
* 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,
|
createHostView(protoViewRef: ProtoViewRef = null, index: number = -1,
|
||||||
dynamicallyCreatedBindings: ResolvedBinding[] = null): HostViewRef {
|
dynamicallyCreatedProviders: ResolvedProvider[] = null): HostViewRef {
|
||||||
if (index == -1) index = this.length;
|
if (index == -1) index = this.length;
|
||||||
return this.viewManager.createHostViewInContainer(this.element, index, protoViewRef,
|
return this.viewManager.createHostViewInContainer(this.element, index, protoViewRef,
|
||||||
dynamicallyCreatedBindings);
|
dynamicallyCreatedProviders);
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO(i): refactor insert+remove into move
|
// TODO(i): refactor insert+remove into move
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
import {
|
import {
|
||||||
Injector,
|
Injector,
|
||||||
Inject,
|
Inject,
|
||||||
Binding,
|
Provider,
|
||||||
Injectable,
|
Injectable,
|
||||||
ResolvedBinding,
|
ResolvedProvider,
|
||||||
forwardRef
|
forwardRef
|
||||||
} from 'angular2/src/core/di';
|
} from 'angular2/src/core/di';
|
||||||
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
|
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
|
||||||
@ -159,7 +159,7 @@ export abstract class AppViewManager {
|
|||||||
*/
|
*/
|
||||||
abstract createHostViewInContainer(viewContainerLocation: ElementRef, index: number,
|
abstract createHostViewInContainer(viewContainerLocation: ElementRef, index: number,
|
||||||
protoViewRef: ProtoViewRef,
|
protoViewRef: ProtoViewRef,
|
||||||
imperativelyCreatedInjector: ResolvedBinding[]): HostViewRef;
|
imperativelyCreatedInjector: ResolvedProvider[]): HostViewRef;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Destroys an Embedded or Host View attached to a View Container at the specified `index`.
|
* 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,
|
createHostViewInContainer(viewContainerLocation: ElementRef, index: number,
|
||||||
protoViewRef: ProtoViewRef,
|
protoViewRef: ProtoViewRef,
|
||||||
imperativelyCreatedInjector: ResolvedBinding[]): HostViewRef {
|
imperativelyCreatedInjector: ResolvedProvider[]): HostViewRef {
|
||||||
var s = this._createHostViewInContainerScope();
|
var s = this._createHostViewInContainerScope();
|
||||||
var protoView = internalProtoView(protoViewRef);
|
var protoView = internalProtoView(protoViewRef);
|
||||||
if (protoView.type !== viewModule.ViewType.HOST) {
|
if (protoView.type !== viewModule.ViewType.HOST) {
|
||||||
@ -297,7 +297,7 @@ export class AppViewManager_ extends AppViewManager {
|
|||||||
*/
|
*/
|
||||||
_createViewInContainer(viewContainerLocation: ElementRef, index: number,
|
_createViewInContainer(viewContainerLocation: ElementRef, index: number,
|
||||||
protoView: viewModule.AppProtoView, context: ElementRef,
|
protoView: viewModule.AppProtoView, context: ElementRef,
|
||||||
imperativelyCreatedInjector: ResolvedBinding[]): ViewRef {
|
imperativelyCreatedInjector: ResolvedProvider[]): ViewRef {
|
||||||
var parentView = internalView((<ElementRef_>viewContainerLocation).parentView);
|
var parentView = internalView((<ElementRef_>viewContainerLocation).parentView);
|
||||||
var boundElementIndex = (<ElementRef_>viewContainerLocation).boundElementIndex;
|
var boundElementIndex = (<ElementRef_>viewContainerLocation).boundElementIndex;
|
||||||
var contextView = internalView((<ElementRef_>context).parentView);
|
var contextView = internalView((<ElementRef_>context).parentView);
|
||||||
|
@ -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 {ListWrapper, MapWrapper, Map, StringMapWrapper} from 'angular2/src/core/facade/collection';
|
||||||
import * as eli from './element_injector';
|
import * as eli from './element_injector';
|
||||||
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
|
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
|
||||||
@ -156,7 +156,7 @@ export class AppViewManagerUtils {
|
|||||||
|
|
||||||
hydrateViewInContainer(parentView: viewModule.AppView, boundElementIndex: number,
|
hydrateViewInContainer(parentView: viewModule.AppView, boundElementIndex: number,
|
||||||
contextView: viewModule.AppView, contextBoundElementIndex: number,
|
contextView: viewModule.AppView, contextBoundElementIndex: number,
|
||||||
index: number, imperativelyCreatedBindings: ResolvedBinding[]) {
|
index: number, imperativelyCreatedProviders: ResolvedProvider[]) {
|
||||||
if (isBlank(contextView)) {
|
if (isBlank(contextView)) {
|
||||||
contextView = parentView;
|
contextView = parentView;
|
||||||
contextBoundElementIndex = boundElementIndex;
|
contextBoundElementIndex = boundElementIndex;
|
||||||
@ -165,8 +165,8 @@ export class AppViewManagerUtils {
|
|||||||
var view = viewContainer.views[index];
|
var view = viewContainer.views[index];
|
||||||
var elementInjector = contextView.elementInjectors[contextBoundElementIndex];
|
var elementInjector = contextView.elementInjectors[contextBoundElementIndex];
|
||||||
|
|
||||||
var injector = isPresent(imperativelyCreatedBindings) ?
|
var injector = isPresent(imperativelyCreatedProviders) ?
|
||||||
Injector.fromResolvedBindings(imperativelyCreatedBindings) :
|
Injector.fromResolvedProviders(imperativelyCreatedProviders) :
|
||||||
null;
|
null;
|
||||||
this._hydrateView(view, injector, elementInjector.getHost(), contextView.context,
|
this._hydrateView(view, injector, elementInjector.getHost(), contextView.context,
|
||||||
contextView.locals);
|
contextView.locals);
|
||||||
|
@ -19,7 +19,8 @@ class Directive extends DirectiveMetadata {
|
|||||||
@deprecated List<String> properties,
|
@deprecated List<String> properties,
|
||||||
@deprecated List<String> events,
|
@deprecated List<String> events,
|
||||||
Map<String, String> host,
|
Map<String, String> host,
|
||||||
List bindings, String exportAs, String moduleId,
|
@deprecated List bindings,
|
||||||
|
List providers, String exportAs, String moduleId,
|
||||||
Map<String, dynamic> queries})
|
Map<String, dynamic> queries})
|
||||||
: super(
|
: super(
|
||||||
selector: selector,
|
selector: selector,
|
||||||
@ -29,6 +30,7 @@ class Directive extends DirectiveMetadata {
|
|||||||
events: events,
|
events: events,
|
||||||
host: host,
|
host: host,
|
||||||
bindings: bindings,
|
bindings: bindings,
|
||||||
|
providers: providers,
|
||||||
exportAs: exportAs,
|
exportAs: exportAs,
|
||||||
moduleId: moduleId,
|
moduleId: moduleId,
|
||||||
queries: queries);
|
queries: queries);
|
||||||
@ -43,9 +45,10 @@ class Component extends ComponentMetadata {
|
|||||||
@deprecated List<String> properties,
|
@deprecated List<String> properties,
|
||||||
@deprecated List<String> events,
|
@deprecated List<String> events,
|
||||||
Map<String, String> host,
|
Map<String, String> host,
|
||||||
List bindings, String exportAs, String moduleId,
|
@deprecated List bindings, List providers, String exportAs, String moduleId,
|
||||||
Map<String, dynamic> queries,
|
Map<String, dynamic> queries,
|
||||||
List viewBindings, ChangeDetectionStrategy changeDetection,
|
@deprecated List viewBindings,
|
||||||
|
List viewProviders, ChangeDetectionStrategy changeDetection,
|
||||||
String templateUrl, String template, dynamic directives,
|
String templateUrl, String template, dynamic directives,
|
||||||
dynamic pipes, ViewEncapsulation encapsulation, List<String> styles,
|
dynamic pipes, ViewEncapsulation encapsulation, List<String> styles,
|
||||||
List<String> styleUrls
|
List<String> styleUrls
|
||||||
@ -58,9 +61,11 @@ class Component extends ComponentMetadata {
|
|||||||
events: events,
|
events: events,
|
||||||
host: host,
|
host: host,
|
||||||
bindings: bindings,
|
bindings: bindings,
|
||||||
|
providers: providers,
|
||||||
exportAs: exportAs,
|
exportAs: exportAs,
|
||||||
moduleId: moduleId,
|
moduleId: moduleId,
|
||||||
viewBindings: viewBindings,
|
viewBindings: viewBindings,
|
||||||
|
viewProviders: viewProviders,
|
||||||
queries: queries,
|
queries: queries,
|
||||||
changeDetection: changeDetection,
|
changeDetection: changeDetection,
|
||||||
templateUrl: templateUrl,
|
templateUrl: templateUrl,
|
||||||
|
@ -153,6 +153,7 @@ export interface DirectiveFactory {
|
|||||||
events?: string[],
|
events?: string[],
|
||||||
host?: {[key: string]: string},
|
host?: {[key: string]: string},
|
||||||
bindings?: any[],
|
bindings?: any[],
|
||||||
|
providers?: any[],
|
||||||
exportAs?: string,
|
exportAs?: string,
|
||||||
moduleId?: string,
|
moduleId?: string,
|
||||||
queries?: {[key: string]: any}
|
queries?: {[key: string]: any}
|
||||||
@ -165,6 +166,7 @@ export interface DirectiveFactory {
|
|||||||
events?: string[],
|
events?: string[],
|
||||||
host?: {[key: string]: string},
|
host?: {[key: string]: string},
|
||||||
bindings?: any[],
|
bindings?: any[],
|
||||||
|
providers?: any[],
|
||||||
exportAs?: string,
|
exportAs?: string,
|
||||||
moduleId?: string,
|
moduleId?: string,
|
||||||
queries?: {[key: string]: any}
|
queries?: {[key: string]: any}
|
||||||
@ -222,11 +224,14 @@ export interface ComponentFactory {
|
|||||||
properties?: string[],
|
properties?: string[],
|
||||||
events?: string[],
|
events?: string[],
|
||||||
host?: {[key: string]: string},
|
host?: {[key: string]: string},
|
||||||
|
/* @deprecated */
|
||||||
bindings?: any[],
|
bindings?: any[],
|
||||||
|
providers?: any[],
|
||||||
exportAs?: string,
|
exportAs?: string,
|
||||||
moduleId?: string,
|
moduleId?: string,
|
||||||
queries?: {[key: string]: any},
|
queries?: {[key: string]: any},
|
||||||
viewBindings?: any[],
|
viewBindings?: any[],
|
||||||
|
viewProviders?: any[],
|
||||||
changeDetection?: ChangeDetectionStrategy,
|
changeDetection?: ChangeDetectionStrategy,
|
||||||
templateUrl?: string,
|
templateUrl?: string,
|
||||||
template?: string,
|
template?: string,
|
||||||
@ -243,11 +248,15 @@ export interface ComponentFactory {
|
|||||||
properties?: string[],
|
properties?: string[],
|
||||||
events?: string[],
|
events?: string[],
|
||||||
host?: {[key: string]: string},
|
host?: {[key: string]: string},
|
||||||
|
/* @deprecated */
|
||||||
bindings?: any[],
|
bindings?: any[],
|
||||||
|
providers?: any[],
|
||||||
exportAs?: string,
|
exportAs?: string,
|
||||||
moduleId?: string,
|
moduleId?: string,
|
||||||
queries?: {[key: string]: any},
|
queries?: {[key: string]: any},
|
||||||
|
/* @deprecated */
|
||||||
viewBindings?: any[],
|
viewBindings?: any[],
|
||||||
|
viewProviders?: any[],
|
||||||
changeDetection?: ChangeDetectionStrategy,
|
changeDetection?: ChangeDetectionStrategy,
|
||||||
templateUrl?: string,
|
templateUrl?: string,
|
||||||
template?: string,
|
template?: string,
|
||||||
|
@ -466,13 +466,13 @@ export class DirectiveMetadata extends InjectableMetadata {
|
|||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
inputs: string[];
|
get inputs(): string[] {
|
||||||
|
return isPresent(this._properties) && this._properties.length > 0 ? this._properties :
|
||||||
/**
|
this._inputs;
|
||||||
* @deprecated
|
}
|
||||||
* Same as `inputs`. This is to enable easier migration.
|
get properties(): string[] { return this.inputs; }
|
||||||
*/
|
private _inputs: string[];
|
||||||
properties: string[];
|
private _properties: string[];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enumerates the set of event-bound output properties.
|
* Enumerates the set of event-bound output properties.
|
||||||
@ -519,13 +519,12 @@ export class DirectiveMetadata extends InjectableMetadata {
|
|||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
outputs: string[];
|
get outputs(): string[] {
|
||||||
|
return isPresent(this._events) && this._events.length > 0 ? this._events : this._outputs;
|
||||||
/**
|
}
|
||||||
* @deprecated
|
get events(): string[] { return this.outputs; }
|
||||||
* Same as `outputs`. This is to enable easier migration.
|
private _outputs: string[];
|
||||||
*/
|
private _events: string[];
|
||||||
events: string[];
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Specify the events, actions, properties and attributes related to the host element.
|
* 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.
|
* 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};
|
queries: {[key: string]: any};
|
||||||
|
|
||||||
constructor({selector, inputs, outputs, properties, events, host, bindings, exportAs, moduleId,
|
constructor({selector, inputs, outputs, properties, events, host, bindings, providers, exportAs,
|
||||||
queries}: {
|
moduleId, queries}: {
|
||||||
selector?: string,
|
selector?: string,
|
||||||
inputs?: string[],
|
inputs?: string[],
|
||||||
outputs?: string[],
|
outputs?: string[],
|
||||||
properties?: string[],
|
properties?: string[],
|
||||||
events?: string[],
|
events?: string[],
|
||||||
host?: {[key: string]: string},
|
host?: {[key: string]: string},
|
||||||
bindings?: any[],
|
providers?: any[],
|
||||||
|
/** @deprecated */ bindings?: any[],
|
||||||
exportAs?: string,
|
exportAs?: string,
|
||||||
moduleId?: string,
|
moduleId?: string,
|
||||||
queries?: {[key: string]: any}
|
queries?: {[key: string]: any}
|
||||||
} = {}) {
|
} = {}) {
|
||||||
super();
|
super();
|
||||||
this.selector = selector;
|
this.selector = selector;
|
||||||
this.inputs = inputs;
|
this._inputs = inputs;
|
||||||
this.outputs = outputs;
|
this._properties = properties;
|
||||||
|
this._outputs = outputs;
|
||||||
|
this._events = events;
|
||||||
this.host = host;
|
this.host = host;
|
||||||
|
|
||||||
// TODO: remove this once properties and events are removed.
|
|
||||||
this.properties = properties;
|
|
||||||
this.events = events;
|
|
||||||
|
|
||||||
this.exportAs = exportAs;
|
this.exportAs = exportAs;
|
||||||
this.moduleId = moduleId;
|
this.moduleId = moduleId;
|
||||||
this.queries = queries;
|
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
|
* When a component is instantiated, Angular
|
||||||
* - creates a shadow DOM for the component.
|
* - creates a shadow DOM for the component.
|
||||||
* - loads the selected template into the shadow DOM.
|
* - 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.
|
* All template expressions and statements are then evaluated against the component instance.
|
||||||
*
|
*
|
||||||
@ -862,7 +867,7 @@ export class ComponentMetadata extends DirectiveMetadata {
|
|||||||
*
|
*
|
||||||
* @Component({
|
* @Component({
|
||||||
* selector: 'greet',
|
* selector: 'greet',
|
||||||
* viewBindings: [
|
* viewProviders: [
|
||||||
* Greeter
|
* 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;
|
templateUrl: string;
|
||||||
|
|
||||||
@ -892,18 +903,21 @@ export class ComponentMetadata extends DirectiveMetadata {
|
|||||||
encapsulation: ViewEncapsulation;
|
encapsulation: ViewEncapsulation;
|
||||||
|
|
||||||
constructor({selector, inputs, outputs, properties, events, host, exportAs, moduleId, bindings,
|
constructor({selector, inputs, outputs, properties, events, host, exportAs, moduleId, bindings,
|
||||||
viewBindings, changeDetection = ChangeDetectionStrategy.Default, queries,
|
providers, viewBindings, viewProviders,
|
||||||
templateUrl, template, styleUrls, styles, directives, pipes, encapsulation}: {
|
changeDetection = ChangeDetectionStrategy.Default, queries, templateUrl, template,
|
||||||
|
styleUrls, styles, directives, pipes, encapsulation}: {
|
||||||
selector?: string,
|
selector?: string,
|
||||||
inputs?: string[],
|
inputs?: string[],
|
||||||
outputs?: string[],
|
outputs?: string[],
|
||||||
properties?: string[],
|
properties?: string[],
|
||||||
events?: string[],
|
events?: string[],
|
||||||
host?: {[key: string]: string},
|
host?: {[key: string]: string},
|
||||||
bindings?: any[],
|
/** @deprecated */ bindings?: any[],
|
||||||
|
providers?: any[],
|
||||||
exportAs?: string,
|
exportAs?: string,
|
||||||
moduleId?: string,
|
moduleId?: string,
|
||||||
viewBindings?: any[],
|
/** @deprecated */ viewBindings?: any[],
|
||||||
|
viewProviders?: any[],
|
||||||
queries?: {[key: string]: any},
|
queries?: {[key: string]: any},
|
||||||
changeDetection?: ChangeDetectionStrategy,
|
changeDetection?: ChangeDetectionStrategy,
|
||||||
templateUrl?: string,
|
templateUrl?: string,
|
||||||
@ -924,12 +938,13 @@ export class ComponentMetadata extends DirectiveMetadata {
|
|||||||
exportAs: exportAs,
|
exportAs: exportAs,
|
||||||
moduleId: moduleId,
|
moduleId: moduleId,
|
||||||
bindings: bindings,
|
bindings: bindings,
|
||||||
|
providers: providers,
|
||||||
queries: queries
|
queries: queries
|
||||||
});
|
});
|
||||||
|
|
||||||
this.changeDetection = changeDetection;
|
this.changeDetection = changeDetection;
|
||||||
this.viewBindings = viewBindings;
|
this._viewProviders = viewProviders;
|
||||||
|
this._viewBindings = viewBindings;
|
||||||
this.templateUrl = templateUrl;
|
this.templateUrl = templateUrl;
|
||||||
this.template = template;
|
this.template = template;
|
||||||
this.styleUrls = styleUrls;
|
this.styleUrls = styleUrls;
|
||||||
|
@ -7,7 +7,7 @@ import {DatePipe} from './date_pipe';
|
|||||||
import {DecimalPipe, PercentPipe, CurrencyPipe} from './number_pipe';
|
import {DecimalPipe, PercentPipe, CurrencyPipe} from './number_pipe';
|
||||||
|
|
||||||
import {CONST_EXPR} from 'angular2/src/core/facade/lang';
|
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([
|
const DEFAULT_PIPES_LIST = CONST_EXPR([
|
||||||
AsyncPipe,
|
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_TOKEN: OpaqueToken = CONST_EXPR(new OpaqueToken("Default Pipes"));
|
||||||
|
|
||||||
export const DEFAULT_PIPES: Binding =
|
export const DEFAULT_PIPES: Provider =
|
||||||
CONST_EXPR(new Binding(DEFAULT_PIPES_TOKEN, {toValue: DEFAULT_PIPES_LIST}));
|
CONST_EXPR(new Provider(DEFAULT_PIPES_TOKEN, {toValue: DEFAULT_PIPES_LIST}));
|
||||||
|
@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
18
modules/angular2/src/core/pipes/pipe_provider.ts
Normal file
18
modules/angular2/src/core/pipes/pipe_provider.ts
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
@ -5,17 +5,17 @@ import {
|
|||||||
Injectable,
|
Injectable,
|
||||||
OptionalMetadata,
|
OptionalMetadata,
|
||||||
SkipSelfMetadata,
|
SkipSelfMetadata,
|
||||||
Binding,
|
Provider,
|
||||||
Injector,
|
Injector,
|
||||||
bind
|
bind
|
||||||
} from 'angular2/src/core/di';
|
} 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';
|
import * as cd from 'angular2/src/core/change_detection/pipes';
|
||||||
|
|
||||||
export class ProtoPipes {
|
export class ProtoPipes {
|
||||||
static fromBindings(bindings: PipeBinding[]): ProtoPipes {
|
static fromProviders(providers: PipeProvider[]): ProtoPipes {
|
||||||
var config: {[key: string]: PipeBinding} = {};
|
var config: {[key: string]: PipeProvider} = {};
|
||||||
bindings.forEach(b => config[b.name] = b);
|
providers.forEach(b => config[b.name] = b);
|
||||||
return new ProtoPipes(config);
|
return new ProtoPipes(config);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -23,14 +23,14 @@ export class ProtoPipes {
|
|||||||
/**
|
/**
|
||||||
* Map of {@link PipeMetadata} names to {@link PipeMetadata} implementations.
|
* Map of {@link PipeMetadata} names to {@link PipeMetadata} implementations.
|
||||||
*/
|
*/
|
||||||
public config: {[key: string]: PipeBinding}) {
|
public config: {[key: string]: PipeProvider}) {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
}
|
}
|
||||||
|
|
||||||
get(name: string): PipeBinding {
|
get(name: string): PipeProvider {
|
||||||
var binding = this.config[name];
|
var provider = this.config[name];
|
||||||
if (isBlank(binding)) throw new BaseException(`Cannot find pipe '${name}'.`);
|
if (isBlank(provider)) throw new BaseException(`Cannot find pipe '${name}'.`);
|
||||||
return binding;
|
return provider;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -7,4 +7,6 @@ import 'package:angular2/src/core/dom/dom_adapter.dart';
|
|||||||
|
|
||||||
exceptionFactory() => new ExceptionHandler(DOM, true);
|
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;
|
||||||
|
@ -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 {ExceptionHandler} from 'angular2/src/core/facade/exceptions';
|
||||||
import {DOM} from 'angular2/src/core/dom/dom_adapter';
|
import {DOM} from 'angular2/src/core/dom/dom_adapter';
|
||||||
|
|
||||||
export const EXCEPTION_BINDING =
|
export const EXCEPTION_PROVIDER =
|
||||||
bind(ExceptionHandler).toFactory(() => new ExceptionHandler(DOM, false), []);
|
provide(ExceptionHandler, {asFactory: () => new ExceptionHandler(DOM, false), deps: []});
|
||||||
|
|
||||||
|
export const EXCEPTION_BINDING = EXCEPTION_PROVIDER;
|
@ -15,8 +15,12 @@ class PublicTestability {
|
|||||||
|
|
||||||
whenStable(callback: Function) { this._testability.whenStable(callback); }
|
whenStable(callback: Function) { this._testability.whenStable(callback); }
|
||||||
|
|
||||||
findBindings(using: any, binding: string, exactMatch: boolean): any[] {
|
findBindings(using: any, provider: string, exactMatch: boolean): any[] {
|
||||||
return this._testability.findBindings(using, binding, exactMatch);
|
return this.findProviders(using, provider, exactMatch);
|
||||||
|
}
|
||||||
|
|
||||||
|
findProviders(using: any, provider: string, exactMatch: boolean): any[] {
|
||||||
|
return this._testability.findBindings(using, provider, exactMatch);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -72,7 +72,12 @@ export class Testability {
|
|||||||
// check for stability.
|
// check for stability.
|
||||||
isAngularEventPending(): boolean { return this._isAngularEventPending; }
|
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.
|
// TODO(juliemr): implement.
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
@ -91,7 +91,7 @@ export class MockConnection implements Connection {
|
|||||||
/**
|
/**
|
||||||
* A mock backend for testing the {@link Http} service.
|
* 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}.
|
* to other backends, such as {@link XHRBackend}.
|
||||||
*
|
*
|
||||||
* #Example
|
* #Example
|
||||||
@ -102,9 +102,9 @@ export class MockConnection implements Connection {
|
|||||||
* var connection;
|
* var connection;
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* MockBackend,
|
* MockBackend,
|
||||||
* bind(Http).toFactory((backend, defaultOptions) => {
|
* provide(Http, {asFactory: (backend, defaultOptions) => {
|
||||||
* return new Http(backend, defaultOptions)
|
* return new Http(backend, defaultOptions)
|
||||||
* }, [MockBackend, DefaultOptions])]);
|
* }, deps: [MockBackend, DefaultOptions]})]);
|
||||||
* var http = injector.get(Http);
|
* var http = injector.get(Http);
|
||||||
* var backend = injector.get(MockBackend);
|
* var backend = injector.get(MockBackend);
|
||||||
* //Assign any newly-created connection to local variable
|
* //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 text; //this will be set from mock response
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* MockBackend,
|
* MockBackend,
|
||||||
* bind(Http).toFactory(backend, options) {
|
* provide(Http, {asFactory: (backend, options) {
|
||||||
* return new Http(backend, options);
|
* return new Http(backend, options);
|
||||||
* }, [MockBackend, BaseRequestOptions]]);
|
* }, deps: [MockBackend, BaseRequestOptions]}]);
|
||||||
* var backend = injector.get(MockBackend);
|
* var backend = injector.get(MockBackend);
|
||||||
* var http = injector.get(Http);
|
* var http = injector.get(Http);
|
||||||
* backend.connections.subscribe(c => connection = c);
|
* backend.connections.subscribe(c => connection = c);
|
||||||
|
@ -91,13 +91,13 @@ export class XHRConnection implements Connection {
|
|||||||
* #Example
|
* #Example
|
||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
* import {Http, MyNodeBackend, HTTP_BINDINGS, BaseRequestOptions} from 'angular2/http';
|
* import {Http, MyNodeBackend, HTTP_PROVIDERS, BaseRequestOptions} from 'angular2/http';
|
||||||
* @Component({
|
* @Component({
|
||||||
* viewBindings: [
|
* viewProviders: [
|
||||||
* HTTP_BINDINGS,
|
* HTTP_PROVIDERS,
|
||||||
* bind(Http).toFactory((backend, options) => {
|
* provide(Http, {asFactory: (backend, options) => {
|
||||||
* return new Http(backend, options);
|
* return new Http(backend, options);
|
||||||
* }, [MyNodeBackend, BaseRequestOptions])]
|
* }, deps: [MyNodeBackend, BaseRequestOptions]})]
|
||||||
* })
|
* })
|
||||||
* class MyComponent {
|
* class MyComponent {
|
||||||
* constructor(http:Http) {
|
* constructor(http:Http) {
|
||||||
|
@ -117,15 +117,15 @@ export class RequestOptions {
|
|||||||
* ### Example ([live demo](http://plnkr.co/edit/LEKVSx?p=preview))
|
* ### Example ([live demo](http://plnkr.co/edit/LEKVSx?p=preview))
|
||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* import {bind, bootstrap} from 'angular2/angular2';
|
* import {provide, bootstrap} from 'angular2/angular2';
|
||||||
* import {HTTP_BINDINGS, Http, BaseRequestOptions, RequestOptions} from 'angular2/http';
|
* import {HTTP_PROVIDERS, Http, BaseRequestOptions, RequestOptions} from 'angular2/http';
|
||||||
* import {App} from './myapp';
|
* import {App} from './myapp';
|
||||||
*
|
*
|
||||||
* class MyOptions extends BaseRequestOptions {
|
* class MyOptions extends BaseRequestOptions {
|
||||||
* search: string = 'coreTeam=true';
|
* 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}
|
* The options could also be extended when manually creating a {@link Request}
|
||||||
|
@ -115,15 +115,16 @@ export class ResponseOptions {
|
|||||||
* ### Example ([live demo](http://plnkr.co/edit/qv8DLT?p=preview))
|
* ### Example ([live demo](http://plnkr.co/edit/qv8DLT?p=preview))
|
||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* import {bind, bootstrap} from 'angular2/angular2';
|
* import {provide, bootstrap} from 'angular2/angular2';
|
||||||
* import {HTTP_BINDINGS, Headers, Http, BaseResponseOptions, ResponseOptions} from 'angular2/http';
|
* import {HTTP_PROVIDERS, Headers, Http, BaseResponseOptions, ResponseOptions} from
|
||||||
|
* 'angular2/http';
|
||||||
* import {App} from './myapp';
|
* import {App} from './myapp';
|
||||||
*
|
*
|
||||||
* class MyOptions extends BaseResponseOptions {
|
* class MyOptions extends BaseResponseOptions {
|
||||||
* headers:Headers = new Headers({network: 'github'});
|
* 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}
|
* The options could also be extended when manually creating a {@link Response}
|
||||||
|
@ -39,8 +39,8 @@ function mergeOptions(defaultOpts, providedOpts, method, url): RequestOptions {
|
|||||||
* #Example
|
* #Example
|
||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* import {Http, HTTP_BINDINGS} from 'angular2/http';
|
* import {Http, HTTP_PROVIDERS} from 'angular2/http';
|
||||||
* @Component({selector: 'http-app', viewBindings: [HTTP_BINDINGS]})
|
* @Component({selector: 'http-app', viewProviders: [HTTP_PROVIDERS]})
|
||||||
* @View({templateUrl: 'people.html'})
|
* @View({templateUrl: 'people.html'})
|
||||||
* class PeopleComponent {
|
* class PeopleComponent {
|
||||||
* constructor(http: Http) {
|
* 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" (
|
* 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
|
* {@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
|
* #Example
|
||||||
*
|
*
|
||||||
@ -72,11 +72,11 @@ function mergeOptions(defaultOpts, providedOpts, method, url): RequestOptions {
|
|||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = Injector.resolveAndCreate([
|
||||||
* BaseRequestOptions,
|
* BaseRequestOptions,
|
||||||
* MockBackend,
|
* MockBackend,
|
||||||
* bind(Http).toFactory(
|
* provide(Http, {asFactory:
|
||||||
* function(backend, defaultOptions) {
|
* function(backend, defaultOptions) {
|
||||||
* return new Http(backend, defaultOptions);
|
* return new Http(backend, defaultOptions);
|
||||||
* },
|
* },
|
||||||
* [MockBackend, BaseRequestOptions])
|
* deps: [MockBackend, BaseRequestOptions]})
|
||||||
* ]);
|
* ]);
|
||||||
* var http = injector.get(Http);
|
* var http = injector.get(Http);
|
||||||
* http.get('request-from-mock-backend.json').subscribe((res:Response) => doSomething(res));
|
* http.get('request-from-mock-backend.json').subscribe((res:Response) => doSomething(res));
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
// Index to be used if Http is ever configured as a standalone npm package.
|
// Index to be used if Http is ever configured as a standalone npm package.
|
||||||
// require('reflect-metadata');
|
// require('reflect-metadata');
|
||||||
// require('es6-shim');
|
// 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';
|
// import {Injector} from 'angular2/angular2';
|
||||||
// export * from './http';
|
// export * from './http';
|
||||||
|
|
||||||
@ -9,5 +9,5 @@
|
|||||||
// * TODO(jeffbcross): export each as their own top-level file, to require as:
|
// * TODO(jeffbcross): export each as their own top-level file, to require as:
|
||||||
// * require('angular2/http'); require('http/jsonp');
|
// * require('angular2/http'); require('http/jsonp');
|
||||||
// */
|
// */
|
||||||
// export var http = Injector.resolveAndCreate([HTTP_BINDINGS]).get(Http);
|
// export var http = Injector.resolveAndCreate([HTTP_PROVIDERS]).get(Http);
|
||||||
// export var jsonp = Injector.resolveAndCreate([JSONP_BINDINGS]).get(Jsonp);
|
// export var jsonp = Injector.resolveAndCreate([JSONP_PROVIDERS]).get(Jsonp);
|
||||||
|
@ -26,7 +26,7 @@ import {
|
|||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* import {Injectable, Injector} from 'angular2/angular2';
|
* 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()
|
* @Injectable()
|
||||||
* class AutoAuthenticator {
|
* 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);
|
* var authenticator = injector.get(AutoAuthenticator);
|
||||||
* authenticator.request('people.json').subscribe(res => {
|
* authenticator.request('people.json').subscribe(res => {
|
||||||
* //URL should have included '?password=123'
|
* //URL should have included '?password=123'
|
||||||
|
@ -4,24 +4,24 @@ import {DirectiveMetadata, ComponentMetadata} from '../core/metadata';
|
|||||||
import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver';
|
import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver';
|
||||||
|
|
||||||
export class MockDirectiveResolver extends DirectiveResolver {
|
export class MockDirectiveResolver extends DirectiveResolver {
|
||||||
private _bindingsOverrides = new Map<Type, any[]>();
|
private _providerOverrides = new Map<Type, any[]>();
|
||||||
private _viewBindingsOverrides = new Map<Type, any[]>();
|
private viewProviderOverrides = new Map<Type, any[]>();
|
||||||
|
|
||||||
resolve(type: Type): DirectiveMetadata {
|
resolve(type: Type): DirectiveMetadata {
|
||||||
var dm = super.resolve(type);
|
var dm = super.resolve(type);
|
||||||
|
|
||||||
var bindingsOverride = this._bindingsOverrides.get(type);
|
var providerOverrides = this._providerOverrides.get(type);
|
||||||
var viewBindingsOverride = this._viewBindingsOverrides.get(type);
|
var viewProviderOverrides = this.viewProviderOverrides.get(type);
|
||||||
|
|
||||||
var bindings = dm.bindings;
|
var providers = dm.providers;
|
||||||
if (isPresent(bindingsOverride)) {
|
if (isPresent(providerOverrides)) {
|
||||||
bindings = dm.bindings.concat(bindingsOverride);
|
providers = dm.providers.concat(providerOverrides);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (dm instanceof ComponentMetadata) {
|
if (dm instanceof ComponentMetadata) {
|
||||||
var viewBindings = dm.viewBindings;
|
var viewProviders = dm.viewProviders;
|
||||||
if (isPresent(viewBindingsOverride)) {
|
if (isPresent(viewProviderOverrides)) {
|
||||||
viewBindings = dm.viewBindings.concat(viewBindingsOverride);
|
viewProviders = dm.viewProviders.concat(viewProviderOverrides);
|
||||||
}
|
}
|
||||||
|
|
||||||
return new ComponentMetadata({
|
return new ComponentMetadata({
|
||||||
@ -29,12 +29,12 @@ export class MockDirectiveResolver extends DirectiveResolver {
|
|||||||
inputs: dm.inputs,
|
inputs: dm.inputs,
|
||||||
outputs: dm.outputs,
|
outputs: dm.outputs,
|
||||||
host: dm.host,
|
host: dm.host,
|
||||||
bindings: bindings,
|
|
||||||
exportAs: dm.exportAs,
|
exportAs: dm.exportAs,
|
||||||
moduleId: dm.moduleId,
|
moduleId: dm.moduleId,
|
||||||
queries: dm.queries,
|
queries: dm.queries,
|
||||||
changeDetection: dm.changeDetection,
|
changeDetection: dm.changeDetection,
|
||||||
viewBindings: viewBindings
|
providers: providers,
|
||||||
|
viewProviders: viewProviders
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -43,18 +43,32 @@ export class MockDirectiveResolver extends DirectiveResolver {
|
|||||||
inputs: dm.inputs,
|
inputs: dm.inputs,
|
||||||
outputs: dm.outputs,
|
outputs: dm.outputs,
|
||||||
host: dm.host,
|
host: dm.host,
|
||||||
bindings: bindings,
|
providers: providers,
|
||||||
exportAs: dm.exportAs,
|
exportAs: dm.exportAs,
|
||||||
moduleId: dm.moduleId,
|
moduleId: dm.moduleId,
|
||||||
queries: dm.queries
|
queries: dm.queries
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated
|
||||||
|
*/
|
||||||
setBindingsOverride(type: Type, bindings: any[]): void {
|
setBindingsOverride(type: Type, bindings: any[]): void {
|
||||||
this._bindingsOverrides.set(type, bindings);
|
this._providerOverrides.set(type, bindings);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated
|
||||||
|
*/
|
||||||
setViewBindingsOverride(type: Type, viewBindings: any[]): void {
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -18,7 +18,7 @@ import {EventListener, History, Location} from 'angular2/src/core/facade/browser
|
|||||||
* import {Component, View} from 'angular2/angular2';
|
* import {Component, View} from 'angular2/angular2';
|
||||||
* import {
|
* import {
|
||||||
* ROUTER_DIRECTIVES,
|
* ROUTER_DIRECTIVES,
|
||||||
* ROUTER_BINDINGS,
|
* ROUTER_PROVIDERS,
|
||||||
* RouteConfig,
|
* RouteConfig,
|
||||||
* Location
|
* Location
|
||||||
* } from 'angular2/router';
|
* } 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()
|
@Injectable()
|
||||||
|
@ -16,7 +16,7 @@ import {Url} from './url_parser';
|
|||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
* import {bootstrap, Component, View} from 'angular2/angular2';
|
* 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({...})
|
* @Component({...})
|
||||||
* @View({directives: [ROUTER_DIRECTIVES]})
|
* @View({directives: [ROUTER_DIRECTIVES]})
|
||||||
@ -34,7 +34,7 @@ import {Url} from './url_parser';
|
|||||||
* }
|
* }
|
||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* bootstrap(AppCmp, ROUTER_BINDINGS);
|
* bootstrap(AppCmp, ROUTER_PROVIDERS);
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
export class RouteParams {
|
export class RouteParams {
|
||||||
@ -54,7 +54,7 @@ export class RouteParams {
|
|||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
* import {bootstrap, Component, View} from 'angular2/angular2';
|
* 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({...})
|
* @Component({...})
|
||||||
* @View({directives: [ROUTER_DIRECTIVES]})
|
* @View({directives: [ROUTER_DIRECTIVES]})
|
||||||
@ -68,7 +68,7 @@ export class RouteParams {
|
|||||||
* }
|
* }
|
||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* bootstrap(AppCmp, ROUTER_BINDINGS);
|
* bootstrap(AppCmp, ROUTER_PROVIDERS);
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
export class Instruction {
|
export class Instruction {
|
||||||
|
@ -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
|
* The `APP_BASE_HREF` token represents the base href to be used with the
|
||||||
* {@link PathLocationStrategy}.
|
* {@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
|
* representing the URL prefix that should be preserved when generating and recognizing
|
||||||
* URLs.
|
* URLs.
|
||||||
*
|
*
|
||||||
@ -17,7 +17,7 @@ import {OpaqueToken, Injectable, Optional, Inject} from 'angular2/src/core/di';
|
|||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
* import {Component, View} from 'angular2/angular2';
|
* 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({...})
|
* @Component({...})
|
||||||
* @View({directives: [ROUTER_DIRECTIVES]})
|
* @View({directives: [ROUTER_DIRECTIVES]})
|
||||||
@ -29,9 +29,9 @@ import {OpaqueToken, Injectable, Optional, Inject} from 'angular2/src/core/di';
|
|||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* bootstrap(AppCmp, [
|
* bootstrap(AppCmp, [
|
||||||
* ROUTER_BINDINGS,
|
* ROUTER_PROVIDERS,
|
||||||
* PathLocationStrategy,
|
* 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 {Component, View} from 'angular2/angular2';
|
||||||
* import {
|
* import {
|
||||||
* ROUTER_DIRECTIVES,
|
* ROUTER_DIRECTIVES,
|
||||||
* ROUTER_BINDINGS,
|
* ROUTER_PROVIDERS,
|
||||||
* RouteConfig,
|
* RouteConfig,
|
||||||
* Location
|
* Location
|
||||||
* } from 'angular2/router';
|
* } 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()
|
@Injectable()
|
||||||
@ -91,7 +91,7 @@ export class Location {
|
|||||||
|
|
||||||
if (isBlank(browserBaseHref)) {
|
if (isBlank(browserBaseHref)) {
|
||||||
throw new BaseException(
|
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));
|
this._baseHref = stripTrailingSlash(stripIndexHtml(browserBaseHref));
|
||||||
|
@ -10,9 +10,9 @@ import {LocationStrategy} from './location_strategy';
|
|||||||
* browser's URL.
|
* browser's URL.
|
||||||
*
|
*
|
||||||
* `PathLocationStrategy` is the default binding for {@link LocationStrategy}
|
* `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
|
* {@link APP_BASE_HREF} to a string representing the URL prefix that should
|
||||||
* be preserved when generating and recognizing URLs.
|
* be preserved when generating and recognizing URLs.
|
||||||
*
|
*
|
||||||
@ -23,11 +23,11 @@ import {LocationStrategy} from './location_strategy';
|
|||||||
* ## Example
|
* ## Example
|
||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
* import {Component, View, bind} from 'angular2/angular2';
|
* import {Component, View, provide} from 'angular2/angular2';
|
||||||
* import {
|
* import {
|
||||||
* APP_BASE_HREF
|
* APP_BASE_HREF
|
||||||
* ROUTER_DIRECTIVES,
|
* ROUTER_DIRECTIVES,
|
||||||
* ROUTER_BINDINGS,
|
* ROUTER_PROVIDERS,
|
||||||
* RouteConfig,
|
* RouteConfig,
|
||||||
* Location
|
* Location
|
||||||
* } from 'angular2/router';
|
* } from 'angular2/router';
|
||||||
@ -44,8 +44,8 @@ import {LocationStrategy} from './location_strategy';
|
|||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* bootstrap(AppCmp, [
|
* bootstrap(AppCmp, [
|
||||||
* ROUTER_BINDINGS, // includes binding to PathLocationStrategy
|
* ROUTER_PROVIDERS, // includes binding to PathLocationStrategy
|
||||||
* bind(APP_BASE_HREF).toValue('/my/app')
|
* provide(APP_BASE_HREF, {asValue: '/my/app'})
|
||||||
* ]);
|
* ]);
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
|
@ -5,7 +5,7 @@ import {BaseException, WrappedException} from 'angular2/src/core/facade/exceptio
|
|||||||
|
|
||||||
import {Directive, Attribute} from 'angular2/src/core/metadata';
|
import {Directive, Attribute} from 'angular2/src/core/metadata';
|
||||||
import {DynamicComponentLoader, ComponentRef, ElementRef} from 'angular2/src/core/linker';
|
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 * as routerMod from './router';
|
||||||
import {ComponentInstruction, RouteParams} from './instruction';
|
import {ComponentInstruction, RouteParams} from './instruction';
|
||||||
@ -50,13 +50,12 @@ export class RouterOutlet {
|
|||||||
var componentType = nextInstruction.componentType;
|
var componentType = nextInstruction.componentType;
|
||||||
var childRouter = this._parentRouter.childRouter(componentType);
|
var childRouter = this._parentRouter.childRouter(componentType);
|
||||||
|
|
||||||
var bindings = Injector.resolve([
|
var providers = Injector.resolve([
|
||||||
bind(ROUTE_DATA)
|
provide(ROUTE_DATA, {asValue: nextInstruction.routeData()}),
|
||||||
.toValue(nextInstruction.routeData()),
|
provide(RouteParams, {asValue: new RouteParams(nextInstruction.params)}),
|
||||||
bind(RouteParams).toValue(new RouteParams(nextInstruction.params)),
|
provide(routerMod.Router, {asValue: childRouter})
|
||||||
bind(routerMod.Router).toValue(childRouter)
|
|
||||||
]);
|
]);
|
||||||
return this._loader.loadNextToLocation(componentType, this._elementRef, bindings)
|
return this._loader.loadNextToLocation(componentType, this._elementRef, providers)
|
||||||
.then((componentRef) => {
|
.then((componentRef) => {
|
||||||
this._componentRef = componentRef;
|
this._componentRef = componentRef;
|
||||||
if (hasLifecycleHook(hookMod.onActivate, componentType)) {
|
if (hasLifecycleHook(hookMod.onActivate, componentType)) {
|
||||||
|
@ -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 {Type, isPresent, isBlank} from 'angular2/src/core/facade/lang';
|
||||||
import {Promise} from 'angular2/src/core/facade/async';
|
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.
|
* 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
|
* The providers specified via this method are appended to the existing `providers` causing the
|
||||||
* duplicated bindings to
|
* duplicated providers to
|
||||||
* be overridden.
|
* be overridden.
|
||||||
*
|
*
|
||||||
* @param {Type} component
|
* @param {Type} component
|
||||||
* @param {any[]} bindings
|
* @param {any[]} providers
|
||||||
*
|
*
|
||||||
* @return {TestComponentBuilder}
|
* @return {TestComponentBuilder}
|
||||||
*/
|
*/
|
||||||
overrideBindings(type: Type, bindings: any[]): TestComponentBuilder {
|
overrideProviders(type: Type, providers: any[]): TestComponentBuilder {
|
||||||
var clone = this._clone();
|
var clone = this._clone();
|
||||||
clone._bindingsOverrides.set(type, bindings);
|
clone._bindingsOverrides.set(type, providers);
|
||||||
return clone;
|
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.
|
* 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
|
* The providers specified via this method are appended to the existing `providers` causing the
|
||||||
* duplicated bindings to
|
* duplicated providers to
|
||||||
* be overridden.
|
* be overridden.
|
||||||
*
|
*
|
||||||
* @param {Type} component
|
* @param {Type} component
|
||||||
* @param {any[]} bindings
|
* @param {any[]} providers
|
||||||
*
|
*
|
||||||
* @return {TestComponentBuilder}
|
* @return {TestComponentBuilder}
|
||||||
*/
|
*/
|
||||||
overrideViewBindings(type: Type, bindings: any[]): TestComponentBuilder {
|
overrideViewProviders(type: Type, providers: any[]): TestComponentBuilder {
|
||||||
var clone = this._clone();
|
var clone = this._clone();
|
||||||
clone._viewBindingsOverrides.set(type, bindings);
|
clone._viewBindingsOverrides.set(type, providers);
|
||||||
return clone;
|
return clone;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated
|
||||||
|
*/
|
||||||
|
overrideViewBindings(type: Type, providers: any[]): TestComponentBuilder {
|
||||||
|
return this.overrideViewProviders(type, providers);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Builds and returns a RootTestComponent.
|
* Builds and returns a RootTestComponent.
|
||||||
*
|
*
|
||||||
|
@ -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 {DEFAULT_PIPES} from 'angular2/src/core/pipes';
|
||||||
import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
|
import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
|
||||||
import {MockAnimationBuilder} from 'angular2/src/mock/animation_builder_mock';
|
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 {TestComponentBuilder} from './test_component_builder';
|
||||||
|
|
||||||
import {Injector} from 'angular2/src/core/di';
|
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 {ListWrapper} from 'angular2/src/core/facade/collection';
|
||||||
import {FunctionWrapper, Type} from 'angular2/src/core/facade/lang';
|
import {FunctionWrapper, Type} from 'angular2/src/core/facade/lang';
|
||||||
@ -56,27 +56,24 @@ import {
|
|||||||
import {APP_ID} from 'angular2/src/core/application_tokens';
|
import {APP_ID} from 'angular2/src/core/application_tokens';
|
||||||
import {Serializer} from "angular2/src/web_workers/shared/serializer";
|
import {Serializer} from "angular2/src/web_workers/shared/serializer";
|
||||||
import {Log} from './utils';
|
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 {DomRenderer_} from "angular2/src/core/render/dom/dom_renderer";
|
||||||
import {DynamicComponentLoader_} from "angular2/src/core/linker/dynamic_component_loader";
|
import {DynamicComponentLoader_} from "angular2/src/core/linker/dynamic_component_loader";
|
||||||
import {AppViewManager_} from "angular2/src/core/linker/view_manager";
|
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
|
* This must be kept in sync with the _rootBindings in application.js
|
||||||
*
|
*
|
||||||
* @returns {any[]}
|
* @returns {any[]}
|
||||||
*/
|
*/
|
||||||
function _getRootBindings() {
|
function _getRootProviders() {
|
||||||
return [
|
return [provide(Reflector, {asValue: reflector})];
|
||||||
bind(Reflector)
|
|
||||||
.toValue(reflector),
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the application injector bindings.
|
* Returns the application injector providers.
|
||||||
*
|
*
|
||||||
* This must be kept in sync with _injectorBindings() in application.js
|
* This must be kept in sync with _injectorBindings() in application.js
|
||||||
*
|
*
|
||||||
@ -93,43 +90,44 @@ function _getAppBindings() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return [
|
return [
|
||||||
compilerBindings(),
|
compilerProviders(),
|
||||||
bind(ChangeDetectorGenConfig).toValue(new ChangeDetectorGenConfig(true, true, false, true)),
|
provide(ChangeDetectorGenConfig,
|
||||||
bind(DOCUMENT).toValue(appDoc),
|
{asValue: new ChangeDetectorGenConfig(true, true, false, true)}),
|
||||||
bind(DomRenderer).toClass(DomRenderer_),
|
provide(DOCUMENT, {asValue: appDoc}),
|
||||||
bind(Renderer).toAlias(DomRenderer),
|
provide(DomRenderer, {asClass: DomRenderer_}),
|
||||||
bind(APP_ID).toValue('a'),
|
provide(Renderer, {asAlias: DomRenderer}),
|
||||||
|
provide(APP_ID, {asValue: 'a'}),
|
||||||
DomSharedStylesHost,
|
DomSharedStylesHost,
|
||||||
bind(SharedStylesHost).toAlias(DomSharedStylesHost),
|
provide(SharedStylesHost, {asAlias: DomSharedStylesHost}),
|
||||||
AppViewPool,
|
AppViewPool,
|
||||||
bind(AppViewManager).toClass(AppViewManager_),
|
provide(AppViewManager, {asClass: AppViewManager_}),
|
||||||
AppViewManagerUtils,
|
AppViewManagerUtils,
|
||||||
Serializer,
|
Serializer,
|
||||||
ELEMENT_PROBE_BINDINGS,
|
ELEMENT_PROBE_PROVIDERS,
|
||||||
bind(APP_VIEW_POOL_CAPACITY).toValue(500),
|
provide(APP_VIEW_POOL_CAPACITY, {asValue: 500}),
|
||||||
ProtoViewFactory,
|
ProtoViewFactory,
|
||||||
bind(DirectiveResolver).toClass(MockDirectiveResolver),
|
provide(DirectiveResolver, {asClass: MockDirectiveResolver}),
|
||||||
bind(ViewResolver).toClass(MockViewResolver),
|
provide(ViewResolver, {asClass: MockViewResolver}),
|
||||||
DEFAULT_PIPES,
|
DEFAULT_PIPES,
|
||||||
bind(IterableDiffers).toValue(defaultIterableDiffers),
|
provide(IterableDiffers, {asValue: defaultIterableDiffers}),
|
||||||
bind(KeyValueDiffers).toValue(defaultKeyValueDiffers),
|
provide(KeyValueDiffers, {asValue: defaultKeyValueDiffers}),
|
||||||
Log,
|
Log,
|
||||||
bind(DynamicComponentLoader).toClass(DynamicComponentLoader_),
|
provide(DynamicComponentLoader, {asClass: DynamicComponentLoader_}),
|
||||||
PipeResolver,
|
PipeResolver,
|
||||||
bind(ExceptionHandler).toValue(new ExceptionHandler(DOM)),
|
provide(ExceptionHandler, {asValue: new ExceptionHandler(DOM)}),
|
||||||
bind(LocationStrategy).toClass(MockLocationStrategy),
|
provide(LocationStrategy, {asClass: MockLocationStrategy}),
|
||||||
bind(XHR).toClass(MockXHR),
|
provide(XHR, {asClass: MockXHR}),
|
||||||
TestComponentBuilder,
|
TestComponentBuilder,
|
||||||
bind(NgZone).toClass(MockNgZone),
|
provide(NgZone, {asClass: MockNgZone}),
|
||||||
bind(AnimationBuilder).toClass(MockAnimationBuilder),
|
provide(AnimationBuilder, {asClass: MockAnimationBuilder}),
|
||||||
EventManager,
|
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 {
|
export function createTestInjector(providers: Array<Type | Provider | any[]>): Injector {
|
||||||
var rootInjector = Injector.resolveAndCreate(_getRootBindings());
|
var rootInjector = Injector.resolveAndCreate(_getRootProviders());
|
||||||
return rootInjector.resolveAndCreateChild(ListWrapper.concat(_getAppBindings(), bindings));
|
return rootInjector.resolveAndCreateChild(ListWrapper.concat(_getAppBindings(), providers));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -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.dart';
|
||||||
import 'package:angular2/src/core/reflection/reflection_capabilities.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/di/injector.dart' show Injector;
|
||||||
import 'package:angular2/src/core/facade/collection.dart' show StringMapWrapper;
|
import 'package:angular2/src/core/facade/collection.dart' show StringMapWrapper;
|
||||||
|
|
||||||
@ -162,13 +162,18 @@ void beforeEach(fn) {
|
|||||||
* bind(SomeToken).toValue(myValue),
|
* bind(SomeToken).toValue(myValue),
|
||||||
* ]);
|
* ]);
|
||||||
*/
|
*/
|
||||||
void beforeEachBindings(Function fn) {
|
void beforeEachProviders(Function fn) {
|
||||||
gns.beforeEach(() {
|
gns.beforeEach(() {
|
||||||
var bindings = fn();
|
var bindings = fn();
|
||||||
if (bindings != null) _testBindings.addAll(bindings);
|
if (bindings != null) _testBindings.addAll(bindings);
|
||||||
}, priority: 2);
|
}, priority: 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Deprecated('using beforeEachProviders instead')
|
||||||
|
void beforeEachBindings(Function fn) {
|
||||||
|
beforeEachProviders(fn);
|
||||||
|
}
|
||||||
|
|
||||||
void _it(gnsFn, name, fn) {
|
void _it(gnsFn, name, fn) {
|
||||||
if (fn is! FunctionWithParamTokens) fn = new FunctionWithParamTokens([], fn);
|
if (fn is! FunctionWithParamTokens) fn = new FunctionWithParamTokens([], fn);
|
||||||
gnsFn(name, () {
|
gnsFn(name, () {
|
||||||
|
@ -3,7 +3,7 @@ import {StringMapWrapper} from 'angular2/src/core/facade/collection';
|
|||||||
import {global, isFunction, Math} from 'angular2/src/core/facade/lang';
|
import {global, isFunction, Math} from 'angular2/src/core/facade/lang';
|
||||||
import {NgZoneZone} from 'angular2/src/core/zone/ng_zone';
|
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 {createTestInjector, FunctionWithParamTokens, inject} from './test_injector';
|
||||||
import {browserDetection} from './utils';
|
import {browserDetection} from './utils';
|
||||||
@ -53,12 +53,12 @@ var runnerStack = [];
|
|||||||
var inIt = false;
|
var inIt = false;
|
||||||
var globalTimeOut = browserDetection.isSlow ? 3000 : jasmine.DEFAULT_TIMEOUT_INTERVAL;
|
var globalTimeOut = browserDetection.isSlow ? 3000 : jasmine.DEFAULT_TIMEOUT_INTERVAL;
|
||||||
|
|
||||||
var testBindings;
|
var testProviders;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mechanism to run `beforeEach()` functions of Angular tests.
|
* 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 {
|
class BeforeEachRunner {
|
||||||
private _fns: Array<FunctionWithParamTokens | SyncTestFn> = [];
|
private _fns: Array<FunctionWithParamTokens | SyncTestFn> = [];
|
||||||
@ -75,8 +75,8 @@ class BeforeEachRunner {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset the test bindings before each test
|
// Reset the test providers before each test
|
||||||
jsmBeforeEach(() => { testBindings = []; });
|
jsmBeforeEach(() => { testProviders = []; });
|
||||||
|
|
||||||
function _describe(jsmFn, ...args) {
|
function _describe(jsmFn, ...args) {
|
||||||
var parentRunner = runnerStack.length === 0 ? null : runnerStack[runnerStack.length - 1];
|
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:
|
* Example:
|
||||||
*
|
*
|
||||||
* beforeEachBindings(() => [
|
* beforeEachBindings(() => [
|
||||||
* bind(Compiler).toClass(MockCompiler),
|
* provide(Compiler, {asClass: MockCompiler}),
|
||||||
* bind(SomeToken).toValue(myValue),
|
* provide(SomeToken, {asValue: myValue}),
|
||||||
* ]);
|
* ]);
|
||||||
*/
|
*/
|
||||||
export function beforeEachBindings(fn): void {
|
export function beforeEachProviders(fn): void {
|
||||||
jsmBeforeEach(() => {
|
jsmBeforeEach(() => {
|
||||||
var bindings = fn();
|
var bindings = fn();
|
||||||
if (!bindings) return;
|
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,
|
function _it(jsmFn: Function, name: string, testFn: FunctionWithParamTokens | AnyTestFn,
|
||||||
testTimeOut: number): void {
|
testTimeOut: number): void {
|
||||||
var runner = runnerStack[runnerStack.length - 1];
|
var runner = runnerStack[runnerStack.length - 1];
|
||||||
@ -140,16 +147,15 @@ function _it(jsmFn: Function, name: string, testFn: FunctionWithParamTokens | An
|
|||||||
|
|
||||||
if (testFn.hasToken(AsyncTestCompleter)) {
|
if (testFn.hasToken(AsyncTestCompleter)) {
|
||||||
jsmFn(name, (done) => {
|
jsmFn(name, (done) => {
|
||||||
var completerBinding =
|
var completerProvider = provide(AsyncTestCompleter, {
|
||||||
bind(AsyncTestCompleter)
|
asFactory: () => {
|
||||||
.toFactory(() => {
|
// Mark the test as async when an AsyncTestCompleter is injected in an it()
|
||||||
// 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()"');
|
||||||
if (!inIt)
|
return new AsyncTestCompleter(done);
|
||||||
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);
|
runner.run(injector);
|
||||||
|
|
||||||
inIt = true;
|
inIt = true;
|
||||||
@ -158,7 +164,7 @@ function _it(jsmFn: Function, name: string, testFn: FunctionWithParamTokens | An
|
|||||||
}, timeOut);
|
}, timeOut);
|
||||||
} else {
|
} else {
|
||||||
jsmFn(name, () => {
|
jsmFn(name, () => {
|
||||||
var injector = createTestInjector(testBindings);
|
var injector = createTestInjector(testProviders);
|
||||||
runner.run(injector);
|
runner.run(injector);
|
||||||
testFn.execute(injector);
|
testFn.execute(injector);
|
||||||
}, timeOut);
|
}, timeOut);
|
||||||
@ -169,13 +175,13 @@ function _it(jsmFn: Function, name: string, testFn: FunctionWithParamTokens | An
|
|||||||
|
|
||||||
if ((<any>testFn).length === 0) {
|
if ((<any>testFn).length === 0) {
|
||||||
jsmFn(name, () => {
|
jsmFn(name, () => {
|
||||||
var injector = createTestInjector(testBindings);
|
var injector = createTestInjector(testProviders);
|
||||||
runner.run(injector);
|
runner.run(injector);
|
||||||
(<SyncTestFn>testFn)();
|
(<SyncTestFn>testFn)();
|
||||||
}, timeOut);
|
}, timeOut);
|
||||||
} else {
|
} else {
|
||||||
jsmFn(name, (done) => {
|
jsmFn(name, (done) => {
|
||||||
var injector = createTestInjector(testBindings);
|
var injector = createTestInjector(testProviders);
|
||||||
runner.run(injector);
|
runner.run(injector);
|
||||||
(<AsyncTestFn>testFn)(done);
|
(<AsyncTestFn>testFn)(done);
|
||||||
}, timeOut);
|
}, timeOut);
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
// TODO (jteplitz602): This whole file is nearly identical to core/application.ts.
|
// 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
|
// 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 {DEFAULT_PIPES} from 'angular2/src/core/pipes';
|
||||||
import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
|
import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
|
||||||
import {BrowserDetails} from 'angular2/src/animate/browser_details';
|
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 {Renderer} from 'angular2/src/core/render/api';
|
||||||
import {AppRootUrl} from 'angular2/src/core/compiler/app_root_url';
|
import {AppRootUrl} from 'angular2/src/core/compiler/app_root_url';
|
||||||
import {DomRenderer, DomRenderer_, DOCUMENT} from 'angular2/src/core/render/render';
|
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 {ElementSchemaRegistry} from 'angular2/src/core/compiler/schema/element_schema_registry';
|
||||||
import {
|
import {
|
||||||
DomElementSchemaRegistry
|
DomElementSchemaRegistry
|
||||||
@ -68,31 +68,30 @@ import {
|
|||||||
var _rootInjector: Injector;
|
var _rootInjector: Injector;
|
||||||
|
|
||||||
// Contains everything that is safe to share between applications.
|
// 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
|
// TODO: This code is nearly identical to core/application. There should be a way to only write it
|
||||||
// once
|
// once
|
||||||
function _injectorBindings(): any[] {
|
function _injectorProviders(): any[] {
|
||||||
return [
|
return [
|
||||||
bind(DOCUMENT)
|
provide(DOCUMENT, {asValue: DOM.defaultDoc()}),
|
||||||
.toValue(DOM.defaultDoc()),
|
|
||||||
EventManager,
|
EventManager,
|
||||||
new Binding(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true}),
|
new Provider(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true}),
|
||||||
new Binding(EVENT_MANAGER_PLUGINS, {toClass: KeyEventsPlugin, multi: true}),
|
new Provider(EVENT_MANAGER_PLUGINS, {toClass: KeyEventsPlugin, multi: true}),
|
||||||
new Binding(EVENT_MANAGER_PLUGINS, {toClass: HammerGesturesPlugin, multi: true}),
|
new Provider(EVENT_MANAGER_PLUGINS, {toClass: HammerGesturesPlugin, multi: true}),
|
||||||
bind(DomRenderer).toClass(DomRenderer_),
|
provide(DomRenderer, {asClass: DomRenderer_}),
|
||||||
bind(Renderer).toAlias(DomRenderer),
|
provide(Renderer, {asAlias: DomRenderer}),
|
||||||
APP_ID_RANDOM_BINDING,
|
APP_ID_RANDOM_PROVIDER,
|
||||||
DomSharedStylesHost,
|
DomSharedStylesHost,
|
||||||
bind(SharedStylesHost).toAlias(DomSharedStylesHost),
|
provide(SharedStylesHost, {asAlias: DomSharedStylesHost}),
|
||||||
Serializer,
|
Serializer,
|
||||||
bind(ON_WEB_WORKER).toValue(false),
|
provide(ON_WEB_WORKER, {asValue: false}),
|
||||||
bind(ElementSchemaRegistry).toValue(new DomElementSchemaRegistry()),
|
provide(ElementSchemaRegistry, {asValue: new DomElementSchemaRegistry()}),
|
||||||
RenderViewWithFragmentsStore,
|
RenderViewWithFragmentsStore,
|
||||||
RenderProtoViewRefStore,
|
RenderProtoViewRefStore,
|
||||||
AppViewPool,
|
AppViewPool,
|
||||||
bind(APP_VIEW_POOL_CAPACITY).toValue(10000),
|
provide(APP_VIEW_POOL_CAPACITY, {asValue: 10000}),
|
||||||
bind(AppViewManager).toClass(AppViewManager_),
|
provide(AppViewManager, {asClass: AppViewManager_}),
|
||||||
AppViewManagerUtils,
|
AppViewManagerUtils,
|
||||||
AppViewListener,
|
AppViewListener,
|
||||||
ProtoViewFactory,
|
ProtoViewFactory,
|
||||||
@ -101,28 +100,28 @@ function _injectorBindings(): any[] {
|
|||||||
DirectiveResolver,
|
DirectiveResolver,
|
||||||
Parser,
|
Parser,
|
||||||
Lexer,
|
Lexer,
|
||||||
bind(ExceptionHandler).toFactory(() => new ExceptionHandler(DOM), []),
|
provide(ExceptionHandler, {asFactory: () => new ExceptionHandler(DOM), deps: []}),
|
||||||
bind(XHR).toValue(new XHRImpl()),
|
provide(XHR, {asValue: new XHRImpl()}),
|
||||||
UrlResolver,
|
UrlResolver,
|
||||||
bind(DynamicComponentLoader).toClass(DynamicComponentLoader_),
|
provide(DynamicComponentLoader, {asClass: DynamicComponentLoader_}),
|
||||||
Testability,
|
Testability,
|
||||||
AnchorBasedAppRootUrl,
|
AnchorBasedAppRootUrl,
|
||||||
bind(AppRootUrl).toAlias(AnchorBasedAppRootUrl),
|
provide(AppRootUrl, {asAlias: AnchorBasedAppRootUrl}),
|
||||||
WebWorkerApplication,
|
WebWorkerApplication,
|
||||||
WebWorkerSetup,
|
WebWorkerSetup,
|
||||||
MessageBasedXHRImpl,
|
MessageBasedXHRImpl,
|
||||||
MessageBasedRenderer,
|
MessageBasedRenderer,
|
||||||
bind(ServiceMessageBrokerFactory).toClass(ServiceMessageBrokerFactory_),
|
provide(ServiceMessageBrokerFactory, {asClass: ServiceMessageBrokerFactory_}),
|
||||||
bind(ClientMessageBrokerFactory).toClass(ClientMessageBrokerFactory_),
|
provide(ClientMessageBrokerFactory, {asClass: ClientMessageBrokerFactory_}),
|
||||||
BrowserDetails,
|
BrowserDetails,
|
||||||
AnimationBuilder,
|
AnimationBuilder
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createInjector(zone: NgZone, bus: MessageBus): Injector {
|
export function createInjector(zone: NgZone, bus: MessageBus): Injector {
|
||||||
BrowserDomAdapter.makeCurrent();
|
BrowserDomAdapter.makeCurrent();
|
||||||
_rootBindings.push(bind(NgZone).toValue(zone));
|
_rootProviders.push(provide(NgZone, {asValue: zone}));
|
||||||
_rootBindings.push(bind(MessageBus).toValue(bus));
|
_rootProviders.push(provide(MessageBus, {asValue: bus}));
|
||||||
var injector: Injector = Injector.resolveAndCreate(_rootBindings);
|
var injector: Injector = Injector.resolveAndCreate(_rootProviders);
|
||||||
return injector.resolveAndCreateChild(_injectorBindings());
|
return injector.resolveAndCreateChild(_injectorProviders());
|
||||||
}
|
}
|
||||||
|
@ -24,7 +24,7 @@ import {
|
|||||||
} from 'angular2/src/web_workers/shared/service_message_broker';
|
} 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
|
* And then creates a new WebWorkerMain object to handle messages from the worker
|
||||||
*/
|
*/
|
||||||
export function bootstrapUICommon(bus: MessageBus): WebWorkerApplication {
|
export function bootstrapUICommon(bus: MessageBus): WebWorkerApplication {
|
||||||
|
@ -4,7 +4,7 @@ import {
|
|||||||
PostMessageBusSource
|
PostMessageBusSource
|
||||||
} from 'angular2/src/web_workers/shared/post_message_bus';
|
} from 'angular2/src/web_workers/shared/post_message_bus';
|
||||||
import {Type} from "angular2/src/core/facade/lang";
|
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 {Map} from 'angular2/src/core/facade/collection';
|
||||||
import {Promise} from 'angular2/src/core/facade/async';
|
import {Promise} from 'angular2/src/core/facade/async';
|
||||||
import {bootstrapWebWorkerCommon} from "angular2/src/web_workers/worker/application_common";
|
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.
|
* See the bootstrap() docs for more details.
|
||||||
*/
|
*/
|
||||||
export function bootstrapWebWorker(
|
export function bootstrapWebWorker(
|
||||||
appComponentType: Type, componentInjectableBindings: Array<Type | Binding | any[]> = null):
|
appComponentType: Type, componentInjectableProviders: Array<Type | Provider | any[]> = null):
|
||||||
Promise<ComponentRef> {
|
Promise<ComponentRef> {
|
||||||
Parse5DomAdapter.makeCurrent();
|
Parse5DomAdapter.makeCurrent();
|
||||||
var sink = new PostMessageBusSink({
|
var sink = new PostMessageBusSink({
|
||||||
@ -40,5 +40,5 @@ export function bootstrapWebWorker(
|
|||||||
var source = new PostMessageBusSource();
|
var source = new PostMessageBusSource();
|
||||||
var bus = new PostMessageBus(sink, source);
|
var bus = new PostMessageBus(sink, source);
|
||||||
|
|
||||||
return bootstrapWebWorkerCommon(appComponentType, bus, componentInjectableBindings);
|
return bootstrapWebWorkerCommon(appComponentType, bus, componentInjectableProviders);
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import {Injector, bind, OpaqueToken, Binding} from 'angular2/src/core/di';
|
import {Injector, provide, OpaqueToken, Provider} from 'angular2/src/core/di';
|
||||||
import {FORM_BINDINGS} from 'angular2/src/core/forms';
|
import {FORM_PROVIDERS} from 'angular2/src/core/forms';
|
||||||
import {
|
import {
|
||||||
NumberWrapper,
|
NumberWrapper,
|
||||||
Type,
|
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 {WebWorkerEventDispatcher} from 'angular2/src/web_workers/worker/event_dispatcher';
|
||||||
import {ComponentRef} from 'angular2/src/core/linker/dynamic_component_loader';
|
import {ComponentRef} from 'angular2/src/core/linker/dynamic_component_loader';
|
||||||
import {NgZone} from 'angular2/src/core/zone/ng_zone';
|
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
|
* 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.
|
* 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:
|
* platform exists:
|
||||||
*
|
*
|
||||||
* If no platform exists, a new one will be created with the default {@link platformBindings}.
|
* 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
|
* was created with). This is a convenience feature, allowing for multiple applications
|
||||||
* to be loaded into the same platform without awareness of each other.
|
* 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
|
* 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
|
* 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.
|
* 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
|
* them if a platform did not exist already. If it did exist, however, an error will be
|
||||||
* thrown.
|
* 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
|
* web worker context. Applications that need direct access to the DOM should
|
||||||
* use `platform` from `core/application_common` instead.
|
* 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);
|
return platformCommon(bindings);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -91,30 +91,30 @@ class PrintLogger {
|
|||||||
logGroupEnd() {}
|
logGroupEnd() {}
|
||||||
}
|
}
|
||||||
|
|
||||||
function webWorkerBindings(appComponentType, bus: MessageBus, initData: {[key: string]: any}):
|
function webWorkerProviders(appComponentType, bus: MessageBus, initData: {[key: string]: any}):
|
||||||
Array<Type | Binding | any[]> {
|
Array<Type | Provider | any[]> {
|
||||||
return [
|
return [
|
||||||
compilerBindings(),
|
compilerProviders(),
|
||||||
Serializer,
|
Serializer,
|
||||||
bind(MessageBus).toValue(bus),
|
provide(MessageBus, {asValue: bus}),
|
||||||
bind(ClientMessageBrokerFactory).toClass(ClientMessageBrokerFactory_),
|
provide(ClientMessageBrokerFactory, {asClass: ClientMessageBrokerFactory_}),
|
||||||
bind(ServiceMessageBrokerFactory).toClass(ServiceMessageBrokerFactory_),
|
provide(ServiceMessageBrokerFactory, {asClass: ServiceMessageBrokerFactory_}),
|
||||||
WebWorkerRenderer,
|
WebWorkerRenderer,
|
||||||
bind(Renderer).toAlias(WebWorkerRenderer),
|
provide(Renderer, {asAlias: WebWorkerRenderer}),
|
||||||
bind(ON_WEB_WORKER).toValue(true),
|
provide(ON_WEB_WORKER, {asValue: true}),
|
||||||
RenderViewWithFragmentsStore,
|
RenderViewWithFragmentsStore,
|
||||||
RenderProtoViewRefStore,
|
RenderProtoViewRefStore,
|
||||||
bind(ExceptionHandler).toFactory(() => new ExceptionHandler(new PrintLogger()), []),
|
provide(ExceptionHandler, {asFactory: () => new ExceptionHandler(new PrintLogger()), deps: []}),
|
||||||
WebWorkerXHRImpl,
|
WebWorkerXHRImpl,
|
||||||
bind(XHR).toAlias(WebWorkerXHRImpl),
|
provide(XHR, {asAlias: WebWorkerXHRImpl}),
|
||||||
bind(AppRootUrl).toValue(new AppRootUrl(initData['rootUrl'])),
|
provide(AppRootUrl, {asValue: new AppRootUrl(initData['rootUrl'])}),
|
||||||
WebWorkerEventDispatcher,
|
WebWorkerEventDispatcher,
|
||||||
FORM_BINDINGS
|
FORM_PROVIDERS
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function bootstrapWebWorkerCommon(appComponentType: Type, bus: MessageBus,
|
export function bootstrapWebWorkerCommon(appComponentType: Type, bus: MessageBus,
|
||||||
appBindings: Array<Type | Binding | any[]> = null):
|
appProviders: Array<Type | Provider | any[]> = null):
|
||||||
Promise<ComponentRef> {
|
Promise<ComponentRef> {
|
||||||
var bootstrapProcess: PromiseCompleter<any> = PromiseWrapper.completer();
|
var bootstrapProcess: PromiseCompleter<any> = PromiseWrapper.completer();
|
||||||
var appPromise = platform().asyncApplication((zone: NgZone) => {
|
var appPromise = platform().asyncApplication((zone: NgZone) => {
|
||||||
@ -128,9 +128,9 @@ export function bootstrapWebWorkerCommon(appComponentType: Type, bus: MessageBus
|
|||||||
var emitter = bus.from(SETUP_CHANNEL);
|
var emitter = bus.from(SETUP_CHANNEL);
|
||||||
subscription = ObservableWrapper.subscribe(emitter, (message: {[key: string]: any}) => {
|
subscription = ObservableWrapper.subscribe(emitter, (message: {[key: string]: any}) => {
|
||||||
var bindings =
|
var bindings =
|
||||||
[applicationCommonBindings(), webWorkerBindings(appComponentType, bus, message)];
|
[applicationCommonBindings(), webWorkerProviders(appComponentType, bus, message)];
|
||||||
if (isPresent(appBindings)) {
|
if (isPresent(appProviders)) {
|
||||||
bindings.push(appBindings);
|
bindings.push(appProviders);
|
||||||
}
|
}
|
||||||
bootstrapProcess.resolve(bindings);
|
bootstrapProcess.resolve(bindings);
|
||||||
ObservableWrapper.dispose(subscription);
|
ObservableWrapper.dispose(subscription);
|
||||||
|
@ -17,7 +17,7 @@ import {Component, Directive, View} from 'angular2/core';
|
|||||||
import {DOM} from 'angular2/src/core/dom/dom_adapter';
|
import {DOM} from 'angular2/src/core/dom/dom_adapter';
|
||||||
import {DOCUMENT} from 'angular2/render';
|
import {DOCUMENT} from 'angular2/render';
|
||||||
import {PromiseWrapper} from 'angular2/src/core/facade/async';
|
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 {ExceptionHandler} from 'angular2/src/core/facade/exceptions';
|
||||||
import {Testability, TestabilityRegistry} from 'angular2/src/core/testability/testability';
|
import {Testability, TestabilityRegistry} from 'angular2/src/core/testability/testability';
|
||||||
import {IS_DART} from '../platform';
|
import {IS_DART} from '../platform';
|
||||||
@ -77,7 +77,7 @@ class _ArrayLogger {
|
|||||||
|
|
||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
var fakeDoc, el, el2, testBindings, lightDom;
|
var fakeDoc, el, el2, testProviders, lightDom;
|
||||||
|
|
||||||
describe('bootstrap factory method', () => {
|
describe('bootstrap factory method', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
@ -89,7 +89,7 @@ export function main() {
|
|||||||
DOM.appendChild(fakeDoc.body, el2);
|
DOM.appendChild(fakeDoc.body, el2);
|
||||||
DOM.appendChild(el, lightDom);
|
DOM.appendChild(el, lightDom);
|
||||||
DOM.setText(lightDom, 'loading');
|
DOM.setText(lightDom, 'loading');
|
||||||
testBindings = [bind(DOCUMENT).toValue(fakeDoc)];
|
testProviders = [provide(DOCUMENT, {asValue: fakeDoc})];
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw if bootstrapped Directive is not a Component',
|
it('should throw if bootstrapped Directive is not a Component',
|
||||||
@ -98,7 +98,7 @@ export function main() {
|
|||||||
var exceptionHandler = new ExceptionHandler(logger, false);
|
var exceptionHandler = new ExceptionHandler(logger, false);
|
||||||
var refPromise =
|
var refPromise =
|
||||||
bootstrap(HelloRootDirectiveIsNotCmp,
|
bootstrap(HelloRootDirectiveIsNotCmp,
|
||||||
[testBindings, bind(ExceptionHandler).toValue(exceptionHandler)]);
|
[testProviders, provide(ExceptionHandler, {asValue: exceptionHandler})]);
|
||||||
|
|
||||||
PromiseWrapper.then(refPromise, null, (exception) => {
|
PromiseWrapper.then(refPromise, null, (exception) => {
|
||||||
expect(exception).toContainError(
|
expect(exception).toContainError(
|
||||||
@ -114,7 +114,7 @@ export function main() {
|
|||||||
var exceptionHandler = new ExceptionHandler(logger, IS_DART ? false : true);
|
var exceptionHandler = new ExceptionHandler(logger, IS_DART ? false : true);
|
||||||
|
|
||||||
var refPromise =
|
var refPromise =
|
||||||
bootstrap(HelloRootCmp, [bind(ExceptionHandler).toValue(exceptionHandler)]);
|
bootstrap(HelloRootCmp, [provide(ExceptionHandler, {asValue: exceptionHandler})]);
|
||||||
PromiseWrapper.then(refPromise, null, (reason) => {
|
PromiseWrapper.then(refPromise, null, (reason) => {
|
||||||
expect(reason.message).toContain('The selector "hello-app" did not match any elements');
|
expect(reason.message).toContain('The selector "hello-app" did not match any elements');
|
||||||
async.done();
|
async.done();
|
||||||
@ -129,7 +129,7 @@ export function main() {
|
|||||||
var exceptionHandler = new ExceptionHandler(logger, IS_DART ? false : true);
|
var exceptionHandler = new ExceptionHandler(logger, IS_DART ? false : true);
|
||||||
|
|
||||||
var refPromise =
|
var refPromise =
|
||||||
bootstrap(HelloRootCmp, [bind(ExceptionHandler).toValue(exceptionHandler)]);
|
bootstrap(HelloRootCmp, [provide(ExceptionHandler, {asValue: exceptionHandler})]);
|
||||||
PromiseWrapper.then(refPromise, null, (reason) => {
|
PromiseWrapper.then(refPromise, null, (reason) => {
|
||||||
expect(logger.res.join(""))
|
expect(logger.res.join(""))
|
||||||
.toContain('The selector "hello-app" did not match any elements');
|
.toContain('The selector "hello-app" did not match any elements');
|
||||||
@ -140,12 +140,12 @@ export function main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
it('should create an injector promise', () => {
|
it('should create an injector promise', () => {
|
||||||
var refPromise = bootstrap(HelloRootCmp, testBindings);
|
var refPromise = bootstrap(HelloRootCmp, testProviders);
|
||||||
expect(refPromise).not.toBe(null);
|
expect(refPromise).not.toBe(null);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should display hello world', inject([AsyncTestCompleter], (async) => {
|
it('should display hello world', inject([AsyncTestCompleter], (async) => {
|
||||||
var refPromise = bootstrap(HelloRootCmp, testBindings);
|
var refPromise = bootstrap(HelloRootCmp, testProviders);
|
||||||
refPromise.then((ref) => {
|
refPromise.then((ref) => {
|
||||||
expect(el).toHaveText('hello world!');
|
expect(el).toHaveText('hello world!');
|
||||||
async.done();
|
async.done();
|
||||||
@ -153,8 +153,8 @@ export function main() {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
it('should support multiple calls to bootstrap', inject([AsyncTestCompleter], (async) => {
|
it('should support multiple calls to bootstrap', inject([AsyncTestCompleter], (async) => {
|
||||||
var refPromise1 = bootstrap(HelloRootCmp, testBindings);
|
var refPromise1 = bootstrap(HelloRootCmp, testProviders);
|
||||||
var refPromise2 = bootstrap(HelloRootCmp2, testBindings);
|
var refPromise2 = bootstrap(HelloRootCmp2, testProviders);
|
||||||
PromiseWrapper.all([refPromise1, refPromise2])
|
PromiseWrapper.all([refPromise1, refPromise2])
|
||||||
.then((refs) => {
|
.then((refs) => {
|
||||||
expect(el).toHaveText('hello world!');
|
expect(el).toHaveText('hello world!');
|
||||||
@ -165,8 +165,8 @@ export function main() {
|
|||||||
|
|
||||||
it("should make the provided bindings available to the application component",
|
it("should make the provided bindings available to the application component",
|
||||||
inject([AsyncTestCompleter], (async) => {
|
inject([AsyncTestCompleter], (async) => {
|
||||||
var refPromise =
|
var refPromise = bootstrap(
|
||||||
bootstrap(HelloRootCmp3, [testBindings, bind("appBinding").toValue("BoundValue")]);
|
HelloRootCmp3, [testProviders, provide("appBinding", {asValue: "BoundValue"})]);
|
||||||
|
|
||||||
refPromise.then((ref) => {
|
refPromise.then((ref) => {
|
||||||
expect(ref.hostComponent.appBinding).toEqual("BoundValue");
|
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",
|
it("should avoid cyclic dependencies when root component requires Lifecycle through DI",
|
||||||
inject([AsyncTestCompleter], (async) => {
|
inject([AsyncTestCompleter], (async) => {
|
||||||
var refPromise = bootstrap(HelloRootCmp4, testBindings);
|
var refPromise = bootstrap(HelloRootCmp4, testProviders);
|
||||||
|
|
||||||
refPromise.then((ref) => {
|
refPromise.then((ref) => {
|
||||||
expect(ref.hostComponent.lc).toBe((<ComponentRef_>ref).injector.get(LifeCycle));
|
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',
|
it('should register each application with the testability registry',
|
||||||
inject([AsyncTestCompleter], (async) => {
|
inject([AsyncTestCompleter], (async) => {
|
||||||
var refPromise1 = bootstrap(HelloRootCmp, testBindings);
|
var refPromise1 = bootstrap(HelloRootCmp, testProviders);
|
||||||
var refPromise2 = bootstrap(HelloRootCmp2, testBindings);
|
var refPromise2 = bootstrap(HelloRootCmp2, testProviders);
|
||||||
|
|
||||||
PromiseWrapper.all([refPromise1, refPromise2])
|
PromiseWrapper.all([refPromise1, refPromise2])
|
||||||
.then((refs: ApplicationRef[]) => {
|
.then((refs: ApplicationRef[]) => {
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/test_lib';
|
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/test_lib';
|
||||||
import {SpyIterableDifferFactory} from '../../spies';
|
import {SpyIterableDifferFactory} from '../../spies';
|
||||||
import {IterableDiffers} from 'angular2/src/core/change_detection/differs/iterable_differs';
|
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() {
|
export function main() {
|
||||||
describe('IterableDiffers', function() {
|
describe('IterableDiffers', function() {
|
||||||
@ -50,7 +50,7 @@ export function main() {
|
|||||||
|
|
||||||
it('should extend di-inherited diffesr', () => {
|
it('should extend di-inherited diffesr', () => {
|
||||||
var parent = new IterableDiffers([factory1]);
|
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])]);
|
var childInjector = injector.resolveAndCreateChild([IterableDiffers.extend([factory2])]);
|
||||||
|
|
||||||
expect(injector.get(IterableDiffers).factories).toEqual([factory1]);
|
expect(injector.get(IterableDiffers).factories).toEqual([factory1]);
|
||||||
|
@ -37,11 +37,11 @@ import {
|
|||||||
} from 'angular2/src/core/compiler/change_definition_factory';
|
} from 'angular2/src/core/compiler/change_definition_factory';
|
||||||
import {TestDirective, TestDispatcher, TestPipes} from './change_detector_mocks';
|
import {TestDirective, TestDispatcher, TestPipes} from './change_detector_mocks';
|
||||||
|
|
||||||
import {TEST_BINDINGS} from './test_bindings';
|
import {TEST_PROVIDERS} from './test_bindings';
|
||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
describe('ChangeDefinitionFactory', () => {
|
describe('ChangeDefinitionFactory', () => {
|
||||||
beforeEachBindings(() => TEST_BINDINGS);
|
beforeEachBindings(() => TEST_PROVIDERS);
|
||||||
|
|
||||||
var parser: TemplateParser;
|
var parser: TemplateParser;
|
||||||
var dispatcher: TestDispatcher;
|
var dispatcher: TestDispatcher;
|
||||||
|
@ -12,7 +12,7 @@ import {
|
|||||||
inject,
|
inject,
|
||||||
beforeEachBindings
|
beforeEachBindings
|
||||||
} from 'angular2/test_lib';
|
} 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 {CONST_EXPR, stringify} from 'angular2/src/core/facade/lang';
|
||||||
import {MapWrapper} from 'angular2/src/core/facade/collection';
|
import {MapWrapper} from 'angular2/src/core/facade/collection';
|
||||||
@ -45,7 +45,7 @@ import {
|
|||||||
|
|
||||||
import {evalModule} from './eval_module';
|
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 {TestDispatcher, TestPipes} from './change_detector_mocks';
|
||||||
import {
|
import {
|
||||||
codeGenValueFn,
|
codeGenValueFn,
|
||||||
@ -60,7 +60,7 @@ var THIS_MODULE_REF = moduleRef(THIS_MODULE_URL);
|
|||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
describe('ChangeDetectorCompiler', () => {
|
describe('ChangeDetectorCompiler', () => {
|
||||||
beforeEachBindings(() => TEST_BINDINGS);
|
beforeEachBindings(() => TEST_PROVIDERS);
|
||||||
|
|
||||||
var parser: TemplateParser;
|
var parser: TemplateParser;
|
||||||
var compiler: ChangeDetectionCompiler;
|
var compiler: ChangeDetectionCompiler;
|
||||||
@ -83,8 +83,8 @@ export function main() {
|
|||||||
|
|
||||||
describe('no jit', () => {
|
describe('no jit', () => {
|
||||||
beforeEachBindings(() => [
|
beforeEachBindings(() => [
|
||||||
bind(ChangeDetectorGenConfig)
|
provide(ChangeDetectorGenConfig,
|
||||||
.toValue(new ChangeDetectorGenConfig(true, true, false, false))
|
{asValue: new ChangeDetectorGenConfig(true, true, false, false)})
|
||||||
]);
|
]);
|
||||||
it('should watch element properties', () => {
|
it('should watch element properties', () => {
|
||||||
expect(detectChanges(compiler, '<div [el-prop]="someProp">'))
|
expect(detectChanges(compiler, '<div [el-prop]="someProp">'))
|
||||||
@ -94,8 +94,8 @@ export function main() {
|
|||||||
|
|
||||||
describe('jit', () => {
|
describe('jit', () => {
|
||||||
beforeEachBindings(() => [
|
beforeEachBindings(() => [
|
||||||
bind(ChangeDetectorGenConfig)
|
provide(ChangeDetectorGenConfig,
|
||||||
.toValue(new ChangeDetectorGenConfig(true, true, false, true))
|
{asValue: new ChangeDetectorGenConfig(true, true, false, true)})
|
||||||
]);
|
]);
|
||||||
it('should watch element properties', () => {
|
it('should watch element properties', () => {
|
||||||
expect(detectChanges(compiler, '<div [el-prop]="someProp">'))
|
expect(detectChanges(compiler, '<div [el-prop]="someProp">'))
|
||||||
|
@ -43,7 +43,7 @@ import {
|
|||||||
codeGenExportVariable,
|
codeGenExportVariable,
|
||||||
MODULE_SUFFIX
|
MODULE_SUFFIX
|
||||||
} from 'angular2/src/core/compiler/util';
|
} from 'angular2/src/core/compiler/util';
|
||||||
import {TEST_BINDINGS} from './test_bindings';
|
import {TEST_PROVIDERS} from './test_bindings';
|
||||||
|
|
||||||
const BEGIN_ELEMENT = 'BEGIN_ELEMENT';
|
const BEGIN_ELEMENT = 'BEGIN_ELEMENT';
|
||||||
const END_ELEMENT = 'END_ELEMENT';
|
const END_ELEMENT = 'END_ELEMENT';
|
||||||
@ -78,7 +78,7 @@ var NESTED_COMPONENT = new CompiledTemplate(45, () => []);
|
|||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
describe('CommandCompiler', () => {
|
describe('CommandCompiler', () => {
|
||||||
beforeEachBindings(() => TEST_BINDINGS);
|
beforeEachBindings(() => TEST_PROVIDERS);
|
||||||
|
|
||||||
var parser: TemplateParser;
|
var parser: TemplateParser;
|
||||||
var commandCompiler: CommandCompiler;
|
var commandCompiler: CommandCompiler;
|
||||||
|
@ -13,7 +13,7 @@ import {
|
|||||||
beforeEachBindings
|
beforeEachBindings
|
||||||
} from 'angular2/test_lib';
|
} 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 {PromiseWrapper} from 'angular2/src/core/facade/async';
|
||||||
import {SpyProtoViewFactory} from '../spies';
|
import {SpyProtoViewFactory} from '../spies';
|
||||||
import {
|
import {
|
||||||
@ -39,7 +39,7 @@ export function main() {
|
|||||||
protoViewFactorySpy = new SpyProtoViewFactory();
|
protoViewFactorySpy = new SpyProtoViewFactory();
|
||||||
someProtoView = new AppProtoView(null, null, null, null, null, null);
|
someProtoView = new AppProtoView(null, null, null, null, null, null);
|
||||||
protoViewFactorySpy.spy('createHost').andReturn(someProtoView);
|
protoViewFactorySpy.spy('createHost').andReturn(someProtoView);
|
||||||
return [bind(ProtoViewFactory).toValue(protoViewFactorySpy)];
|
return [provide(ProtoViewFactory, {asValue: protoViewFactorySpy})];
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should compile the template via TemplateCompiler',
|
it('should compile the template via TemplateCompiler',
|
||||||
|
@ -33,12 +33,12 @@ import {
|
|||||||
SimpleChange
|
SimpleChange
|
||||||
} from 'angular2/core';
|
} 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';
|
import {MODULE_SUFFIX, IS_DART} from 'angular2/src/core/compiler/util';
|
||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
describe('RuntimeMetadataResolver', () => {
|
describe('RuntimeMetadataResolver', () => {
|
||||||
beforeEachBindings(() => TEST_BINDINGS);
|
beforeEachBindings(() => TEST_PROVIDERS);
|
||||||
|
|
||||||
describe('getMetadata', () => {
|
describe('getMetadata', () => {
|
||||||
it('should read metadata',
|
it('should read metadata',
|
||||||
|
@ -12,7 +12,7 @@ import {
|
|||||||
inject,
|
inject,
|
||||||
beforeEachBindings
|
beforeEachBindings
|
||||||
} from 'angular2/test_lib';
|
} from 'angular2/test_lib';
|
||||||
import {bind} from 'angular2/src/core/di';
|
import {provide} from 'angular2/src/core/di';
|
||||||
import {SpyXHR} from '../spies';
|
import {SpyXHR} from '../spies';
|
||||||
import {XHR} from 'angular2/src/core/compiler/xhr';
|
import {XHR} from 'angular2/src/core/compiler/xhr';
|
||||||
import {BaseException, WrappedException} from 'angular2/src/core/facade/exceptions';
|
import {BaseException, WrappedException} from 'angular2/src/core/facade/exceptions';
|
||||||
@ -28,7 +28,7 @@ import {
|
|||||||
} from 'angular2/src/core/compiler/directive_metadata';
|
} from 'angular2/src/core/compiler/directive_metadata';
|
||||||
import {SourceExpression, SourceModule} from 'angular2/src/core/compiler/source_module';
|
import {SourceExpression, SourceModule} from 'angular2/src/core/compiler/source_module';
|
||||||
import {ViewEncapsulation} from 'angular2/src/core/metadata/view';
|
import {ViewEncapsulation} from 'angular2/src/core/metadata/view';
|
||||||
import {TEST_BINDINGS} from './test_bindings';
|
import {TEST_PROVIDERS} from './test_bindings';
|
||||||
import {
|
import {
|
||||||
codeGenValueFn,
|
codeGenValueFn,
|
||||||
codeGenExportVariable,
|
codeGenExportVariable,
|
||||||
@ -51,7 +51,7 @@ export function main() {
|
|||||||
|
|
||||||
beforeEachBindings(() => {
|
beforeEachBindings(() => {
|
||||||
xhr = <any>new SpyXHR();
|
xhr = <any>new SpyXHR();
|
||||||
return [TEST_BINDINGS, bind(XHR).toValue(xhr)];
|
return [TEST_PROVIDERS, provide(XHR, {asValue: xhr})];
|
||||||
});
|
});
|
||||||
|
|
||||||
var compiler: StyleCompiler;
|
var compiler: StyleCompiler;
|
||||||
|
@ -42,9 +42,9 @@ import {
|
|||||||
CompiledTemplate
|
CompiledTemplate
|
||||||
} from 'angular2/src/core/linker/template_commands';
|
} 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 {TestDispatcher, TestPipes} from './change_detector_mocks';
|
||||||
import {
|
import {
|
||||||
codeGenValueFn,
|
codeGenValueFn,
|
||||||
@ -64,7 +64,7 @@ export function main() {
|
|||||||
var compiler: TemplateCompiler;
|
var compiler: TemplateCompiler;
|
||||||
var runtimeMetadataResolver: RuntimeMetadataResolver;
|
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],
|
beforeEach(inject([TemplateCompiler, RuntimeMetadataResolver],
|
||||||
(_compiler, _runtimeMetadataResolver) => {
|
(_compiler, _runtimeMetadataResolver) => {
|
||||||
compiler = _compiler;
|
compiler = _compiler;
|
||||||
|
@ -22,13 +22,13 @@ import {ViewEncapsulation} from 'angular2/src/core/metadata/view';
|
|||||||
import {TemplateNormalizer} from 'angular2/src/core/compiler/template_normalizer';
|
import {TemplateNormalizer} from 'angular2/src/core/compiler/template_normalizer';
|
||||||
import {XHR} from 'angular2/src/core/compiler/xhr';
|
import {XHR} from 'angular2/src/core/compiler/xhr';
|
||||||
import {MockXHR} from 'angular2/src/core/compiler/xhr_mock';
|
import {MockXHR} from 'angular2/src/core/compiler/xhr_mock';
|
||||||
import {TEST_BINDINGS} from './test_bindings';
|
import {TEST_PROVIDERS} from './test_bindings';
|
||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
describe('TemplateNormalizer', () => {
|
describe('TemplateNormalizer', () => {
|
||||||
var dirType: CompileTypeMetadata;
|
var dirType: CompileTypeMetadata;
|
||||||
|
|
||||||
beforeEachBindings(() => TEST_BINDINGS);
|
beforeEachBindings(() => TEST_PROVIDERS);
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
dirType = new CompileTypeMetadata({moduleUrl: 'package:some/module/a.js', name: 'SomeComp'});
|
dirType = new CompileTypeMetadata({moduleUrl: 'package:some/module/a.js', name: 'SomeComp'});
|
||||||
|
@ -10,9 +10,9 @@ import {
|
|||||||
inject,
|
inject,
|
||||||
beforeEachBindings
|
beforeEachBindings
|
||||||
} from 'angular2/test_lib';
|
} 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 {isPresent} from 'angular2/src/core/facade/lang';
|
||||||
import {TemplateParser, splitClasses} from 'angular2/src/core/compiler/template_parser';
|
import {TemplateParser, splitClasses} from 'angular2/src/core/compiler/template_parser';
|
||||||
import {
|
import {
|
||||||
@ -48,9 +48,12 @@ var expressionUnparser = new Unparser();
|
|||||||
export function main() {
|
export function main() {
|
||||||
describe('TemplateParser', () => {
|
describe('TemplateParser', () => {
|
||||||
beforeEachBindings(() => [
|
beforeEachBindings(() => [
|
||||||
TEST_BINDINGS,
|
TEST_PROVIDERS,
|
||||||
bind(ElementSchemaRegistry)
|
provide(ElementSchemaRegistry,
|
||||||
.toValue(new MockSchemaRegistry({'invalidProp': false}, {'mappedAttr': 'mappedProp'}))
|
{
|
||||||
|
asValue: new MockSchemaRegistry({'invalidProp': false},
|
||||||
|
{'mappedAttr': 'mappedProp'})
|
||||||
|
})
|
||||||
]);
|
]);
|
||||||
|
|
||||||
var parser: TemplateParser;
|
var parser: TemplateParser;
|
||||||
|
@ -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 {MockSchemaRegistry} from './schema_registry_mock';
|
||||||
import {ElementSchemaRegistry} from 'angular2/src/core/compiler/schema/element_schema_registry';
|
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({}, {})})];
|
||||||
|
@ -61,7 +61,7 @@ class ChildComp {
|
|||||||
constructor() { this.childBinding = 'Original'; }
|
constructor() { this.childBinding = 'Original'; }
|
||||||
}
|
}
|
||||||
|
|
||||||
@Component({selector: 'parent-comp', viewBindings: [Logger]})
|
@Component({selector: 'parent-comp', viewProviders: [Logger]})
|
||||||
@View({
|
@View({
|
||||||
template: `<div class="parent" message="parent">
|
template: `<div class="parent" message="parent">
|
||||||
<span class="parentnested" message="nestedparent">Parent</span>
|
<span class="parentnested" message="nestedparent">Parent</span>
|
||||||
@ -105,7 +105,7 @@ class EventsComp {
|
|||||||
handleCustom() { this.customed = true; }
|
handleCustom() { this.customed = true; }
|
||||||
}
|
}
|
||||||
|
|
||||||
@Component({selector: 'using-for', viewBindings: [Logger]})
|
@Component({selector: 'using-for', viewProviders: [Logger]})
|
||||||
@View({
|
@View({
|
||||||
template: `<span *ng-for="#thing of stuff" [inner-html]="thing"></span>
|
template: `<span *ng-for="#thing of stuff" [inner-html]="thing"></span>
|
||||||
<ul message="list">
|
<ul message="list">
|
||||||
|
@ -15,7 +15,7 @@ import {
|
|||||||
} from 'angular2/test_lib';
|
} from 'angular2/test_lib';
|
||||||
import {global} from 'angular2/src/core/facade/lang';
|
import {global} from 'angular2/src/core/facade/lang';
|
||||||
import {APP_VIEW_POOL_CAPACITY} from 'angular2/src/core/linker/view_pool';
|
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 {inspectNativeElement} from 'angular2/src/core/debug';
|
||||||
import {IS_DART} from '../../platform';
|
import {IS_DART} from '../../platform';
|
||||||
|
|
||||||
@ -28,7 +28,7 @@ class MyComp {
|
|||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
describe('element probe', function() {
|
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',
|
it('should return a TestElement from a dom element',
|
||||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||||
|
@ -10,21 +10,21 @@ import {
|
|||||||
xit,
|
xit,
|
||||||
} from 'angular2/test_lib';
|
} from 'angular2/test_lib';
|
||||||
|
|
||||||
import {bind} from 'angular2/core';
|
import {bind, provide} from 'angular2/core';
|
||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
describe('binding', () => {
|
describe('provider', () => {
|
||||||
|
|
||||||
describe('type errors', () => {
|
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); })
|
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); })
|
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!');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -4,8 +4,8 @@ import {describe, ddescribe, it, iit, expect, beforeEach} from 'angular2/test_li
|
|||||||
import {SpyDependencyProvider} from '../spies';
|
import {SpyDependencyProvider} from '../spies';
|
||||||
import {
|
import {
|
||||||
Injector,
|
Injector,
|
||||||
bind,
|
provide,
|
||||||
ResolvedBinding,
|
ResolvedProvider,
|
||||||
Key,
|
Key,
|
||||||
forwardRef,
|
forwardRef,
|
||||||
Injectable,
|
Injectable,
|
||||||
@ -15,16 +15,16 @@ import {
|
|||||||
SkipSelfMetadata,
|
SkipSelfMetadata,
|
||||||
Optional,
|
Optional,
|
||||||
Inject,
|
Inject,
|
||||||
Binding
|
Provider
|
||||||
} from 'angular2/core';
|
} from 'angular2/core';
|
||||||
import {DependencyMetadata} from 'angular2/src/core/di/metadata';
|
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 {
|
import {
|
||||||
InjectorInlineStrategy,
|
InjectorInlineStrategy,
|
||||||
InjectorDynamicStrategy,
|
InjectorDynamicStrategy,
|
||||||
ProtoInjector,
|
ProtoInjector,
|
||||||
BindingWithVisibility,
|
ProviderWithVisibility,
|
||||||
Visibility
|
Visibility
|
||||||
} from 'angular2/src/core/di/injector';
|
} from 'angular2/src/core/di/injector';
|
||||||
|
|
||||||
@ -89,29 +89,28 @@ class NoAnnotations {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
var dynamicBindings = [
|
var dynamicProviders = [
|
||||||
bind('binding0')
|
provide('provider0', {asValue: 1}),
|
||||||
.toValue(1),
|
provide('provider1', {asValue: 1}),
|
||||||
bind('binding1').toValue(1),
|
provide('provider2', {asValue: 1}),
|
||||||
bind('binding2').toValue(1),
|
provide('provider3', {asValue: 1}),
|
||||||
bind('binding3').toValue(1),
|
provide('provider4', {asValue: 1}),
|
||||||
bind('binding4').toValue(1),
|
provide('provider5', {asValue: 1}),
|
||||||
bind('binding5').toValue(1),
|
provide('provider6', {asValue: 1}),
|
||||||
bind('binding6').toValue(1),
|
provide('provider7', {asValue: 1}),
|
||||||
bind('binding7').toValue(1),
|
provide('provider8', {asValue: 1}),
|
||||||
bind('binding8').toValue(1),
|
provide('provider9', {asValue: 1}),
|
||||||
bind('binding9').toValue(1),
|
provide('provider10', {asValue: 1})
|
||||||
bind('binding10').toValue(1)
|
|
||||||
];
|
];
|
||||||
|
|
||||||
[{strategy: 'inline', bindings: [], strategyClass: InjectorInlineStrategy},
|
[{strategy: 'inline', providers: [], strategyClass: InjectorInlineStrategy},
|
||||||
{
|
{
|
||||||
strategy: 'dynamic',
|
strategy: 'dynamic',
|
||||||
bindings: dynamicBindings,
|
providers: dynamicProviders,
|
||||||
strategyClass: InjectorDynamicStrategy
|
strategyClass: InjectorDynamicStrategy
|
||||||
}].forEach((context) => {
|
}].forEach((context) => {
|
||||||
function createInjector(bindings: any[]) {
|
function createInjector(providers: any[]) {
|
||||||
return Injector.resolveAndCreate(bindings.concat(context['bindings']));
|
return Injector.resolveAndCreate(providers.concat(context['providers']));
|
||||||
}
|
}
|
||||||
|
|
||||||
describe(`injector ${context['strategy']}`, () => {
|
describe(`injector ${context['strategy']}`, () => {
|
||||||
@ -158,32 +157,33 @@ export function main() {
|
|||||||
expect(e1).toBe(e2);
|
expect(e1).toBe(e2);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should bind to a value', () => {
|
it('should provide to a value', () => {
|
||||||
var injector = createInjector([bind(Engine).toValue("fake engine")]);
|
var injector = createInjector([provide(Engine, {asValue: "fake engine"})]);
|
||||||
|
|
||||||
var engine = injector.get(Engine);
|
var engine = injector.get(Engine);
|
||||||
expect(engine).toEqual("fake 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); }
|
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);
|
var car = injector.get(Car);
|
||||||
expect(car).toBeAnInstanceOf(SportsCar);
|
expect(car).toBeAnInstanceOf(SportsCar);
|
||||||
expect(car.engine).toBeAnInstanceOf(Engine);
|
expect(car.engine).toBeAnInstanceOf(Engine);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should supporting binding to null', () => {
|
it('should supporting provider to null', () => {
|
||||||
var injector = createInjector([bind(Engine).toValue(null)]);
|
var injector = createInjector([provide(Engine, {asValue: null})]);
|
||||||
var engine = injector.get(Engine);
|
var engine = injector.get(Engine);
|
||||||
expect(engine).toBeNull();
|
expect(engine).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should bind to an alias', () => {
|
it('should provide to an alias', () => {
|
||||||
var injector = createInjector(
|
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 car = injector.get(Car);
|
||||||
var sportsCar = injector.get(SportsCar);
|
var sportsCar = injector.get(SportsCar);
|
||||||
@ -191,11 +191,11 @@ export function main() {
|
|||||||
expect(car).toBe(sportsCar);
|
expect(car).toBe(sportsCar);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support multibindings', () => {
|
it('should support multiProviders', () => {
|
||||||
var injector = createInjector([
|
var injector = createInjector([
|
||||||
Engine,
|
Engine,
|
||||||
new Binding(Car, {toClass: SportsCar, multi: true}),
|
new Provider(Car, {toClass: SportsCar, multi: true}),
|
||||||
new Binding(Car, {toClass: CarWithOptionalEngine, multi: true})
|
new Provider(Car, {toClass: CarWithOptionalEngine, multi: true})
|
||||||
]);
|
]);
|
||||||
|
|
||||||
var cars = injector.get(Car);
|
var cars = injector.get(Car);
|
||||||
@ -204,37 +204,32 @@ export function main() {
|
|||||||
expect(cars[1]).toBeAnInstanceOf(CarWithOptionalEngine);
|
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(
|
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);
|
var cars = injector.get(Car);
|
||||||
expect(cars.length).toEqual(1);
|
expect(cars.length).toEqual(1);
|
||||||
expect(cars[0]).toBe(injector.get(SportsCar));
|
expect(cars[0]).toBe(injector.get(SportsCar));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw when the aliased binding does not exist', () => {
|
it('should throw when the aliased provider does not exist', () => {
|
||||||
var injector = createInjector([bind('car').toAlias(SportsCar)]);
|
var injector = createInjector([provide('car', {asAlias: SportsCar})]);
|
||||||
var e = `No provider for ${stringify(SportsCar)}! (car -> ${stringify(SportsCar)})`;
|
var e = `No provider for ${stringify(SportsCar)}! (car -> ${stringify(SportsCar)})`;
|
||||||
expect(() => injector.get('car')).toThrowError(e);
|
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', () => {
|
it('should handle forwardRef in toAlias', () => {
|
||||||
var injector = createInjector([
|
var injector = createInjector([
|
||||||
bind('originalEngine')
|
provide('originalEngine', {asClass: forwardRef(() => Engine)}),
|
||||||
.toClass(forwardRef(() => Engine)),
|
provide('aliasedEngine', {asAlias:<any>forwardRef(() => 'originalEngine')})
|
||||||
bind('aliasedEngine').toAlias(<any>forwardRef(() => 'originalEngine'))
|
|
||||||
]);
|
]);
|
||||||
expect(injector.get('aliasedEngine')).toBeAnInstanceOf(Engine);
|
expect(injector.get('aliasedEngine')).toBeAnInstanceOf(Engine);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support overriding factory dependencies', () => {
|
it('should support overriding factory dependencies', () => {
|
||||||
var injector =
|
var injector = createInjector(
|
||||||
createInjector([Engine, bind(Car).toFactory((e) => new SportsCar(e), [Engine])]);
|
[Engine, provide(Car, {asFactory: (e) => new SportsCar(e), deps: [Engine]})]);
|
||||||
|
|
||||||
var car = injector.get(Car);
|
var car = injector.get(Car);
|
||||||
expect(car).toBeAnInstanceOf(SportsCar);
|
expect(car).toBeAnInstanceOf(SportsCar);
|
||||||
@ -248,33 +243,30 @@ export function main() {
|
|||||||
expect(car.engine).toEqual(null);
|
expect(car.engine).toEqual(null);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should flatten passed-in bindings", () => {
|
it("should flatten passed-in providers", () => {
|
||||||
var injector = createInjector([[[Engine, Car]]]);
|
var injector = createInjector([[[Engine, Car]]]);
|
||||||
|
|
||||||
var car = injector.get(Car);
|
var car = injector.get(Car);
|
||||||
expect(car).toBeAnInstanceOf(Car);
|
expect(car).toBeAnInstanceOf(Car);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should use the last binding when there are multiple bindings for same token", () => {
|
it("should use the last provider when there are multiple providers for same token", () => {
|
||||||
var injector =
|
var injector = createInjector(
|
||||||
createInjector([bind(Engine).toClass(Engine), bind(Engine).toClass(TurboEngine)]);
|
[provide(Engine, {asClass: Engine}), provide(Engine, {asClass: TurboEngine})]);
|
||||||
|
|
||||||
expect(injector.get(Engine)).toBeAnInstanceOf(TurboEngine);
|
expect(injector.get(Engine)).toBeAnInstanceOf(TurboEngine);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should use non-type tokens', () => {
|
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');
|
expect(injector.get('token')).toEqual('value');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw when given invalid bindings', () => {
|
it('should throw when given invalid providers', () => {
|
||||||
expect(() => createInjector(<any>["blah"]))
|
expect(() => createInjector(<any>["blah"]))
|
||||||
.toThrowError(
|
.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');
|
||||||
expect(() => createInjector(<any>[bind("blah")]))
|
|
||||||
.toThrowError('Invalid binding - only instances of Binding and Type are allowed, ' +
|
|
||||||
'got: blah');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should provide itself', () => {
|
it('should provide itself', () => {
|
||||||
@ -297,7 +289,7 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should throw when trying to instantiate a cyclic dependency', () => {
|
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))
|
expect(() => injector.get(Car))
|
||||||
.toThrowError(
|
.toThrowError(
|
||||||
@ -305,10 +297,10 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should show the full path when error happens in a constructor', () => {
|
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([
|
var proto = new ProtoInjector([
|
||||||
new BindingWithVisibility(bindings[0], Visibility.Public),
|
new ProviderWithVisibility(providers[0], Visibility.Public),
|
||||||
new BindingWithVisibility(bindings[1], Visibility.Public)
|
new ProviderWithVisibility(providers[1], Visibility.Public)
|
||||||
]);
|
]);
|
||||||
var injector = new Injector(proto, null, null);
|
var injector = new Injector(proto, null, null);
|
||||||
|
|
||||||
@ -324,13 +316,13 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should provide context when throwing an exception ', () => {
|
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 =
|
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 =
|
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 parent = new Injector(protoParent, null, null, () => "parentContext");
|
||||||
var child = new Injector(protoChild, parent, null, () => "childContext");
|
var child = new Injector(protoChild, parent, null, () => "childContext");
|
||||||
@ -346,8 +338,10 @@ export function main() {
|
|||||||
it('should instantiate an object after a failed attempt', () => {
|
it('should instantiate an object after a failed attempt', () => {
|
||||||
var isBroken = true;
|
var isBroken = true;
|
||||||
|
|
||||||
var injector = createInjector(
|
var injector = createInjector([
|
||||||
[Car, bind(Engine).toFactory(() => isBroken ? new BrokenEngine() : new Engine())]);
|
Car,
|
||||||
|
provide(Engine, {asFactory: (() => isBroken ? new BrokenEngine() : new Engine())})
|
||||||
|
]);
|
||||||
|
|
||||||
expect(() => injector.get(Car)).toThrowError(new RegExp("Error"));
|
expect(() => injector.get(Car)).toThrowError(new RegExp("Error"));
|
||||||
|
|
||||||
@ -357,7 +351,7 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should support null values', () => {
|
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);
|
expect(injector.get('null')).toBe(null);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -367,14 +361,15 @@ export function main() {
|
|||||||
var depProvider = <any>new SpyDependencyProvider();
|
var depProvider = <any>new SpyDependencyProvider();
|
||||||
depProvider.spy("getDependency").andReturn(e);
|
depProvider.spy("getDependency").andReturn(e);
|
||||||
|
|
||||||
var bindings = Injector.resolve([Car]);
|
var providers = Injector.resolve([Car]);
|
||||||
var proto = new ProtoInjector([new BindingWithVisibility(bindings[0], Visibility.Public)]);
|
var proto =
|
||||||
|
new ProtoInjector([new ProviderWithVisibility(providers[0], Visibility.Public)]);
|
||||||
var injector = new Injector(proto, null, depProvider);
|
var injector = new Injector(proto, null, depProvider);
|
||||||
|
|
||||||
expect(injector.get(Car).engine).toEqual(e);
|
expect(injector.get(Car).engine).toEqual(e);
|
||||||
expect(depProvider.spy("getDependency"))
|
expect(depProvider.spy("getDependency"))
|
||||||
.toHaveBeenCalledWith(injector, bindings[0],
|
.toHaveBeenCalledWith(injector, providers[0],
|
||||||
bindings[0].resolvedFactories[0].dependencies[0]);
|
providers[0].resolvedFactories[0].dependencies[0]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -390,10 +385,10 @@ export function main() {
|
|||||||
expect(engineFromChild).toBe(engineFromParent);
|
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 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);
|
var carFromChild = child.get(Car);
|
||||||
expect(carFromChild.engine).toBeAnInstanceOf(Engine);
|
expect(carFromChild.engine).toBeAnInstanceOf(Engine);
|
||||||
@ -401,7 +396,7 @@ export function main() {
|
|||||||
|
|
||||||
it('should create new instance in a child injector', () => {
|
it('should create new instance in a child injector', () => {
|
||||||
var parent = Injector.resolveAndCreate([Engine]);
|
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 engineFromParent = parent.get(Engine);
|
||||||
var engineFromChild = child.get(Engine);
|
var engineFromChild = child.get(Engine);
|
||||||
@ -444,16 +439,18 @@ export function main() {
|
|||||||
describe("depedency resolution", () => {
|
describe("depedency resolution", () => {
|
||||||
describe("@Self()", () => {
|
describe("@Self()", () => {
|
||||||
it("should return a dependency from self", () => {
|
it("should return a dependency from self", () => {
|
||||||
var inj = Injector.resolveAndCreate(
|
var inj = Injector.resolveAndCreate([
|
||||||
[Engine, bind(Car).toFactory((e) => new Car(e), [[Engine, new SelfMetadata()]])]);
|
Engine,
|
||||||
|
provide(Car, {asFactory: (e) => new Car(e), deps: [[Engine, new SelfMetadata()]]})
|
||||||
|
]);
|
||||||
|
|
||||||
expect(inj.get(Car)).toBeAnInstanceOf(Car);
|
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 parent = Injector.resolveAndCreate([Engine]);
|
||||||
var child = parent.resolveAndCreateChild(
|
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))
|
expect(() => child.get(Car))
|
||||||
.toThrowError(`No provider for Engine! (${stringify(Car)} -> ${stringify(Engine)})`);
|
.toThrowError(`No provider for Engine! (${stringify(Car)} -> ${stringify(Engine)})`);
|
||||||
@ -464,7 +461,7 @@ export function main() {
|
|||||||
it("should return a dependency from same host", () => {
|
it("should return a dependency from same host", () => {
|
||||||
var parent = Injector.resolveAndCreate([Engine]);
|
var parent = Injector.resolveAndCreate([Engine]);
|
||||||
var child = parent.resolveAndCreateChild(
|
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);
|
expect(child.get(Car)).toBeAnInstanceOf(Car);
|
||||||
});
|
});
|
||||||
@ -472,11 +469,11 @@ export function main() {
|
|||||||
it("should return a private dependency declared at the host", () => {
|
it("should return a private dependency declared at the host", () => {
|
||||||
var engine = Injector.resolve([Engine])[0];
|
var engine = Injector.resolve([Engine])[0];
|
||||||
var protoParent =
|
var protoParent =
|
||||||
new ProtoInjector([new BindingWithVisibility(engine, Visibility.Private)]);
|
new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Private)]);
|
||||||
var parent = new Injector(protoParent);
|
var parent = new Injector(protoParent);
|
||||||
|
|
||||||
var child = Injector.resolveAndCreate(
|
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
|
child.internalStrategy.attach(parent, true); // host
|
||||||
|
|
||||||
@ -486,11 +483,11 @@ export function main() {
|
|||||||
it("should not return a public dependency declared at the host", () => {
|
it("should not return a public dependency declared at the host", () => {
|
||||||
var engine = Injector.resolve([Engine])[0];
|
var engine = Injector.resolve([Engine])[0];
|
||||||
var protoParent =
|
var protoParent =
|
||||||
new ProtoInjector([new BindingWithVisibility(engine, Visibility.Public)]);
|
new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Public)]);
|
||||||
var parent = new Injector(protoParent);
|
var parent = new Injector(protoParent);
|
||||||
|
|
||||||
var child = Injector.resolveAndCreate(
|
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
|
child.internalStrategy.attach(parent, true); // host
|
||||||
|
|
||||||
@ -501,9 +498,8 @@ export function main() {
|
|||||||
it("should not skip self", () => {
|
it("should not skip self", () => {
|
||||||
var parent = Injector.resolveAndCreate([Engine]);
|
var parent = Injector.resolveAndCreate([Engine]);
|
||||||
var child = parent.resolveAndCreateChild([
|
var child = parent.resolveAndCreateChild([
|
||||||
bind(Engine)
|
provide(Engine, {asClass: TurboEngine}),
|
||||||
.toClass(TurboEngine),
|
provide(Car, {asFactory: (e) => new Car(e), deps: [[Engine, new HostMetadata()]]})
|
||||||
bind(Car).toFactory((e) => new Car(e), [[Engine, new HostMetadata()]])
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
expect(child.get(Car).engine).toBeAnInstanceOf(TurboEngine);
|
expect(child.get(Car).engine).toBeAnInstanceOf(TurboEngine);
|
||||||
@ -514,13 +510,13 @@ export function main() {
|
|||||||
it("should return a private dependency declared at the host", () => {
|
it("should return a private dependency declared at the host", () => {
|
||||||
var engine = Injector.resolve([Engine])[0];
|
var engine = Injector.resolve([Engine])[0];
|
||||||
var protoParent =
|
var protoParent =
|
||||||
new ProtoInjector([new BindingWithVisibility(engine, Visibility.Private)]);
|
new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Private)]);
|
||||||
var parent = new Injector(protoParent);
|
var parent = new Injector(protoParent);
|
||||||
|
|
||||||
var child = Injector.resolveAndCreate([
|
var child = Injector.resolveAndCreate([
|
||||||
bind(Engine)
|
provide(Engine, {asClass: BrokenEngine}),
|
||||||
.toClass(BrokenEngine),
|
provide(Car,
|
||||||
bind(Car).toFactory((e) => new Car(e), [[Engine, new SkipSelfMetadata()]])
|
{asFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]})
|
||||||
]);
|
]);
|
||||||
child.internalStrategy.attach(parent, true); // boundary
|
child.internalStrategy.attach(parent, true); // boundary
|
||||||
|
|
||||||
@ -530,13 +526,13 @@ export function main() {
|
|||||||
it("should return a public dependency declared at the host", () => {
|
it("should return a public dependency declared at the host", () => {
|
||||||
var engine = Injector.resolve([Engine])[0];
|
var engine = Injector.resolve([Engine])[0];
|
||||||
var protoParent =
|
var protoParent =
|
||||||
new ProtoInjector([new BindingWithVisibility(engine, Visibility.Public)]);
|
new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Public)]);
|
||||||
var parent = new Injector(protoParent);
|
var parent = new Injector(protoParent);
|
||||||
|
|
||||||
var child = Injector.resolveAndCreate([
|
var child = Injector.resolveAndCreate([
|
||||||
bind(Engine)
|
provide(Engine, {asClass: BrokenEngine}),
|
||||||
.toClass(BrokenEngine),
|
provide(Car,
|
||||||
bind(Car).toFactory((e) => new Car(e), [[Engine, new SkipSelfMetadata()]])
|
{asFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]})
|
||||||
]);
|
]);
|
||||||
child.internalStrategy.attach(parent, true); // boundary
|
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", () => {
|
it("should not return a private dependency declared NOT at the host", () => {
|
||||||
var engine = Injector.resolve([Engine])[0];
|
var engine = Injector.resolve([Engine])[0];
|
||||||
var protoParent =
|
var protoParent =
|
||||||
new ProtoInjector([new BindingWithVisibility(engine, Visibility.Private)]);
|
new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Private)]);
|
||||||
var parent = new Injector(protoParent);
|
var parent = new Injector(protoParent);
|
||||||
|
|
||||||
var child = Injector.resolveAndCreate([
|
var child = Injector.resolveAndCreate([
|
||||||
bind(Engine)
|
provide(Engine, {asClass: BrokenEngine}),
|
||||||
.toClass(BrokenEngine),
|
provide(Car,
|
||||||
bind(Car).toFactory((e) => new Car(e), [[Engine, new SkipSelfMetadata()]])
|
{asFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]})
|
||||||
]);
|
]);
|
||||||
child.internalStrategy.attach(parent, false);
|
child.internalStrategy.attach(parent, false);
|
||||||
|
|
||||||
@ -563,9 +559,8 @@ export function main() {
|
|||||||
it("should not skip self", () => {
|
it("should not skip self", () => {
|
||||||
var parent = Injector.resolveAndCreate([Engine]);
|
var parent = Injector.resolveAndCreate([Engine]);
|
||||||
var child = parent.resolveAndCreateChild([
|
var child = parent.resolveAndCreateChild([
|
||||||
bind(Engine)
|
provide(Engine, {asClass: TurboEngine}),
|
||||||
.toClass(TurboEngine),
|
provide(Car, {asFactory: (e) => new Car(e), deps: [Engine]})
|
||||||
bind(Car).toFactory((e) => new Car(e), [Engine])
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
expect(child.get(Car).engine).toBeAnInstanceOf(TurboEngine);
|
expect(child.get(Car).engine).toBeAnInstanceOf(TurboEngine);
|
||||||
@ -575,70 +570,73 @@ export function main() {
|
|||||||
|
|
||||||
describe('resolve', () => {
|
describe('resolve', () => {
|
||||||
it('should resolve and flatten', () => {
|
it('should resolve and flatten', () => {
|
||||||
var bindings = Injector.resolve([Engine, [BrokenEngine]]);
|
var providers = Injector.resolve([Engine, [BrokenEngine]]);
|
||||||
bindings.forEach(function(b) {
|
providers.forEach(function(b) {
|
||||||
if (isBlank(b)) return; // the result is a sparse array
|
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", () => {
|
it("should support multi providers", () => {
|
||||||
var binding = Injector.resolve([
|
var provider = Injector.resolve([
|
||||||
new Binding(Engine, {toClass: BrokenEngine, multi: true}),
|
new Provider(Engine, {toClass: BrokenEngine, multi: true}),
|
||||||
new Binding(Engine, {toClass: TurboEngine, multi: true})
|
new Provider(Engine, {toClass: TurboEngine, multi: true})
|
||||||
])[0];
|
])[0];
|
||||||
|
|
||||||
expect(binding.key.token).toBe(Engine);
|
expect(provider.key.token).toBe(Engine);
|
||||||
expect(binding.multiBinding).toEqual(true);
|
expect(provider.multiProvider).toEqual(true);
|
||||||
expect(binding.resolvedFactories.length).toEqual(2);
|
expect(provider.resolvedFactories.length).toEqual(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should support multi bindings with only one binding", () => {
|
it("should support multi providers with only one provider", () => {
|
||||||
var binding =
|
var provider =
|
||||||
Injector.resolve([new Binding(Engine, {toClass: BrokenEngine, multi: true})])[0];
|
Injector.resolve([new Provider(Engine, {toClass: BrokenEngine, multi: true})])[0];
|
||||||
|
|
||||||
expect(binding.key.token).toBe(Engine);
|
expect(provider.key.token).toBe(Engine);
|
||||||
expect(binding.multiBinding).toEqual(true);
|
expect(provider.multiProvider).toEqual(true);
|
||||||
expect(binding.resolvedFactories.length).toEqual(1);
|
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(() => {
|
expect(() => {
|
||||||
Injector.resolve([new Binding(Engine, {toClass: BrokenEngine, multi: true}), Engine]);
|
Injector.resolve([new Provider(Engine, {toClass: BrokenEngine, multi: true}), Engine]);
|
||||||
}).toThrowErrorWith("Cannot mix multi bindings and regular bindings");
|
}).toThrowErrorWith("Cannot mix multi providers and regular providers");
|
||||||
|
|
||||||
expect(() => {
|
expect(() => {
|
||||||
Injector.resolve([Engine, new Binding(Engine, {toClass: BrokenEngine, multi: true})]);
|
Injector.resolve([Engine, new Provider(Engine, {toClass: BrokenEngine, multi: true})]);
|
||||||
}).toThrowErrorWith("Cannot mix multi bindings and regular bindings");
|
}).toThrowErrorWith("Cannot mix multi providers and regular providers");
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should resolve forward references', () => {
|
it('should resolve forward references', () => {
|
||||||
var bindings = Injector.resolve([
|
var providers = Injector.resolve([
|
||||||
forwardRef(() => Engine),
|
forwardRef(() => Engine),
|
||||||
[bind(forwardRef(() => BrokenEngine)).toClass(forwardRef(() => Engine))],
|
[provide(forwardRef(() => BrokenEngine), {asClass: forwardRef(() => Engine)})],
|
||||||
bind(forwardRef(() => String)).toFactory(() => 'OK', [forwardRef(() => Engine)])
|
provide(forwardRef(() => String),
|
||||||
|
{asFactory: () => 'OK', deps: [forwardRef(() => Engine)]})
|
||||||
]);
|
]);
|
||||||
|
|
||||||
var engineBinding = bindings[0];
|
var engineProvider = providers[0];
|
||||||
var brokenEngineBinding = bindings[1];
|
var brokenEngineProvider = providers[1];
|
||||||
var stringBinding = bindings[2];
|
var stringProvider = providers[2];
|
||||||
|
|
||||||
expect(engineBinding.resolvedFactories[0].factory() instanceof Engine).toBe(true);
|
expect(engineProvider.resolvedFactories[0].factory() instanceof Engine).toBe(true);
|
||||||
expect(brokenEngineBinding.resolvedFactories[0].factory() instanceof Engine).toBe(true);
|
expect(brokenEngineProvider.resolvedFactories[0].factory() instanceof Engine).toBe(true);
|
||||||
expect(stringBinding.resolvedFactories[0].dependencies[0].key).toEqual(Key.get(Engine));
|
expect(stringProvider.resolvedFactories[0].dependencies[0].key).toEqual(Key.get(Engine));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support overriding factory dependencies with dependency annotations', () => {
|
it('should support overriding factory dependencies with dependency annotations', () => {
|
||||||
var bindings = Injector.resolve([
|
var providers = Injector.resolve([
|
||||||
bind("token")
|
provide("token",
|
||||||
.toFactory((e) => "result",
|
{
|
||||||
[[new InjectMetadata("dep"), new CustomDependencyMetadata()]])
|
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(provider.resolvedFactories[0].dependencies[0].key.token).toEqual("dep");
|
||||||
expect(binding.resolvedFactories[0].dependencies[0].properties)
|
expect(provider.resolvedFactories[0].dependencies[0].properties)
|
||||||
.toEqual([new CustomDependencyMetadata()]);
|
.toEqual([new CustomDependencyMetadata()]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@ -646,7 +644,7 @@ export function main() {
|
|||||||
describe("displayName", () => {
|
describe("displayName", () => {
|
||||||
it("should work", () => {
|
it("should work", () => {
|
||||||
expect(Injector.resolveAndCreate([Engine, BrokenEngine]).displayName)
|
expect(Injector.resolveAndCreate([Engine, BrokenEngine]).displayName)
|
||||||
.toEqual('Injector(bindings: [ "Engine" , "BrokenEngine" ])');
|
.toEqual('Injector(providers: [ "Engine" , "BrokenEngine" ])');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -15,7 +15,7 @@ import {
|
|||||||
xit,
|
xit,
|
||||||
} from 'angular2/test_lib';
|
} from 'angular2/test_lib';
|
||||||
import {ListWrapper, StringMapWrapper} from 'angular2/src/core/facade/collection';
|
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 {NgClass} from 'angular2/src/core/directives/ng_class';
|
||||||
import {APP_VIEW_POOL_CAPACITY} from 'angular2/src/core/linker/view_pool';
|
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('binding to CSS class list', () => {
|
||||||
|
|
||||||
describe('viewpool support', () => {
|
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',
|
it('should clean up when the directive is destroyed',
|
||||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||||
|
@ -12,6 +12,7 @@ import {
|
|||||||
} from 'angular2/test_lib';
|
} from 'angular2/test_lib';
|
||||||
import {
|
import {
|
||||||
bind,
|
bind,
|
||||||
|
provide,
|
||||||
forwardRef,
|
forwardRef,
|
||||||
resolveForwardRef,
|
resolveForwardRef,
|
||||||
Component,
|
Component,
|
||||||
@ -39,7 +40,7 @@ export function main() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Component({selector: 'app', viewBindings: [forwardRef(() => Frame)]})
|
@Component({selector: 'app', viewProviders: [forwardRef(() => Frame)]})
|
||||||
@View({
|
@View({
|
||||||
template: `<door><lock></lock></door>`,
|
template: `<door><lock></lock></door>`,
|
||||||
directives: [forwardRef(() => Door), forwardRef(() => Lock)]
|
directives: [forwardRef(() => Door), forwardRef(() => Lock)]
|
||||||
|
@ -13,7 +13,7 @@ import {
|
|||||||
beforeEachBindings
|
beforeEachBindings
|
||||||
} from 'angular2/test_lib';
|
} from 'angular2/test_lib';
|
||||||
|
|
||||||
import {Component, View, bind} from 'angular2/core';
|
import {Component, View, provide} from 'angular2/core';
|
||||||
import {SpyProtoViewFactory} from '../spies';
|
import {SpyProtoViewFactory} from '../spies';
|
||||||
import {
|
import {
|
||||||
CompiledHostTemplate,
|
CompiledHostTemplate,
|
||||||
@ -37,10 +37,10 @@ export function main() {
|
|||||||
protoViewFactorySpy = new SpyProtoViewFactory();
|
protoViewFactorySpy = new SpyProtoViewFactory();
|
||||||
someProtoView = new AppProtoView(null, null, null, null, null, null);
|
someProtoView = new AppProtoView(null, null, null, null, null, null);
|
||||||
protoViewFactorySpy.spy('createHost').andReturn(someProtoView);
|
protoViewFactorySpy.spy('createHost').andReturn(someProtoView);
|
||||||
var factoryBinding = bind(ProtoViewFactory).toValue(protoViewFactorySpy);
|
var factory = provide(ProtoViewFactory, {asValue: protoViewFactorySpy});
|
||||||
var classBinding = bind(Compiler).toClass(Compiler_);
|
var classProvider = provide(Compiler, {asClass: Compiler_});
|
||||||
var bindings = [factoryBinding, classBinding];
|
var providers = [factory, classProvider];
|
||||||
return bindings;
|
return providers;
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(inject([Compiler], (_compiler) => {
|
beforeEach(inject([Compiler], (_compiler) => {
|
||||||
|
@ -47,8 +47,6 @@ class SomeDirectiveWithProperties {
|
|||||||
class SomeDirectiveWithEvents {
|
class SomeDirectiveWithEvents {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Directive({selector: 'someDirective'})
|
@Directive({selector: 'someDirective'})
|
||||||
class SomeDirectiveWithSetterProps {
|
class SomeDirectiveWithSetterProps {
|
||||||
@Input("renamed")
|
@Input("renamed")
|
||||||
@ -143,11 +141,6 @@ export function main() {
|
|||||||
expect(directiveMetadata.inputs).toEqual(['a: renamed']);
|
expect(directiveMetadata.inputs).toEqual(['a: renamed']);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should use properties as inputs', () => {
|
|
||||||
var directiveMetadata = resolver.resolve(SomeDirectiveWithProperties);
|
|
||||||
expect(directiveMetadata.inputs).toEqual(['a']);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('outputs', () => {
|
describe('outputs', () => {
|
||||||
@ -160,11 +153,6 @@ export function main() {
|
|||||||
var directiveMetadata = resolver.resolve(SomeDirectiveWithGetterOutputs);
|
var directiveMetadata = resolver.resolve(SomeDirectiveWithGetterOutputs);
|
||||||
expect(directiveMetadata.outputs).toEqual(['a: renamed']);
|
expect(directiveMetadata.outputs).toEqual(['a: renamed']);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should use events as outputs', () => {
|
|
||||||
var directiveMetadata = resolver.resolve(SomeDirectiveWithEvents);
|
|
||||||
expect(directiveMetadata.outputs).toEqual(['a']);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('host', () => {
|
describe('host', () => {
|
||||||
|
@ -270,7 +270,7 @@ class ChildComp {
|
|||||||
|
|
||||||
class DynamicallyCreatedComponentService {}
|
class DynamicallyCreatedComponentService {}
|
||||||
|
|
||||||
@Component({selector: 'hello-cmp', viewBindings: [DynamicallyCreatedComponentService]})
|
@Component({selector: 'hello-cmp', viewProviders: [DynamicallyCreatedComponentService]})
|
||||||
@View({template: "{{greeting}}"})
|
@View({template: "{{greeting}}"})
|
||||||
class DynamicallyCreatedCmp implements OnDestroy {
|
class DynamicallyCreatedCmp implements OnDestroy {
|
||||||
greeting: string;
|
greeting: string;
|
||||||
|
@ -27,7 +27,7 @@ import {
|
|||||||
ProtoElementInjector,
|
ProtoElementInjector,
|
||||||
ElementInjector,
|
ElementInjector,
|
||||||
PreBuiltObjects,
|
PreBuiltObjects,
|
||||||
DirectiveBinding,
|
DirectiveProvider,
|
||||||
TreeNode
|
TreeNode
|
||||||
} from 'angular2/src/core/linker/element_injector';
|
} from 'angular2/src/core/linker/element_injector';
|
||||||
import {
|
import {
|
||||||
@ -38,7 +38,7 @@ import {
|
|||||||
DirectiveMetadata
|
DirectiveMetadata
|
||||||
} from 'angular2/src/core/metadata';
|
} from 'angular2/src/core/metadata';
|
||||||
import {OnDestroy} from 'angular2/lifecycle_hooks';
|
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 {ViewContainerRef, ViewContainerRef_} from 'angular2/src/core/linker/view_container_ref';
|
||||||
import {TemplateRef, TemplateRef_} from 'angular2/src/core/linker/template_ref';
|
import {TemplateRef, TemplateRef_} from 'angular2/src/core/linker/template_ref';
|
||||||
import {ElementRef} from 'angular2/src/core/linker/element_ref';
|
import {ElementRef} from 'angular2/src/core/linker/element_ref';
|
||||||
@ -228,25 +228,25 @@ class DirectiveWithDestroy implements OnDestroy {
|
|||||||
export function main() {
|
export function main() {
|
||||||
var defaultPreBuiltObjects = new PreBuiltObjects(null, createDummyView(), <any>new SpyElementRef(), null);
|
var defaultPreBuiltObjects = new PreBuiltObjects(null, createDummyView(), <any>new SpyElementRef(), null);
|
||||||
|
|
||||||
// An injector with more than 10 bindings will switch to the dynamic strategy
|
// An injector with more than 10 providers will switch to the dynamic strategy
|
||||||
var dynamicBindings = [];
|
var dynamicProviders = [];
|
||||||
|
|
||||||
for (var i = 0; i < 20; i++) {
|
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) {
|
function createPei(parent, index, providers: any[], distance = 1, hasShadowRoot = false, dirVariableBindings = null) {
|
||||||
var directiveBinding = bindings.map(b => {
|
var directiveProvider = providers.map(b => {
|
||||||
if (b instanceof DirectiveBinding) return b;
|
if (b instanceof DirectiveProvider) return b;
|
||||||
if (b instanceof Binding) return DirectiveBinding.createFromBinding(b, null);
|
if (b instanceof Provider) return DirectiveProvider.createFromProvider(b, null);
|
||||||
return DirectiveBinding.createFromType(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) {
|
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;
|
proto.attributes = attributes;
|
||||||
|
|
||||||
var inj = proto.instantiate(null);
|
var inj = proto.instantiate(null);
|
||||||
@ -255,28 +255,28 @@ export function main() {
|
|||||||
return inj;
|
return inj;
|
||||||
}
|
}
|
||||||
|
|
||||||
function parentChildInjectors(parentBindings, childBindings, parentPreBuildObjects = null, imperativelyCreatedInjector = null) {
|
function parentChildInjectors(parentProviders, childProviders, parentPreBuildObjects = null, imperativelyCreatedInjector = null) {
|
||||||
if (isBlank(parentPreBuildObjects)) parentPreBuildObjects = defaultPreBuiltObjects;
|
if (isBlank(parentPreBuildObjects)) parentPreBuildObjects = defaultPreBuiltObjects;
|
||||||
|
|
||||||
var protoParent = createPei(null, 0, parentBindings);
|
var protoParent = createPei(null, 0, parentProviders);
|
||||||
var parent = protoParent.instantiate(null);
|
var parent = protoParent.instantiate(null);
|
||||||
|
|
||||||
parent.hydrate(null, null, parentPreBuildObjects);
|
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);
|
var child = protoChild.instantiate(parent);
|
||||||
child.hydrate(imperativelyCreatedInjector, null, defaultPreBuiltObjects);
|
child.hydrate(imperativelyCreatedInjector, null, defaultPreBuiltObjects);
|
||||||
|
|
||||||
return child;
|
return child;
|
||||||
}
|
}
|
||||||
|
|
||||||
function hostShadowInjectors(hostBindings: any[],
|
function hostShadowInjectors(hostProviders: any[],
|
||||||
shadowBindings: any[], imperativelyCreatedInjector = null): ElementInjector {
|
shadowProviders: any[], imperativelyCreatedInjector = null): ElementInjector {
|
||||||
var protoHost = createPei(null, 0, hostBindings, 0, true);
|
var protoHost = createPei(null, 0, hostProviders, 0, true);
|
||||||
var host = protoHost.instantiate(null);
|
var host = protoHost.instantiate(null);
|
||||||
host.hydrate(null, null, defaultPreBuiltObjects);
|
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);
|
var shadow = protoShadow.instantiate(null);
|
||||||
shadow.hydrate(imperativelyCreatedInjector, host, null);
|
shadow.hydrate(imperativelyCreatedInjector, host, null);
|
||||||
|
|
||||||
@ -321,33 +321,33 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('inline strategy', () => {
|
describe('inline strategy', () => {
|
||||||
it("should allow for direct access using getBindingAtIndex", () => {
|
it("should allow for direct access using getProviderAtIndex", () => {
|
||||||
var proto = createPei(null, 0, [bind(SimpleDirective).toClass(SimpleDirective)]);
|
var proto = createPei(null, 0, [provide(SimpleDirective, {asClass: SimpleDirective})]);
|
||||||
|
|
||||||
expect(proto.getBindingAtIndex(0)).toBeAnInstanceOf(DirectiveBinding);
|
expect(proto.getProviderAtIndex(0)).toBeAnInstanceOf(DirectiveProvider);
|
||||||
expect(() => proto.getBindingAtIndex(-1)).toThrowError('Index -1 is out-of-bounds.');
|
expect(() => proto.getProviderAtIndex(-1)).toThrowError('Index -1 is out-of-bounds.');
|
||||||
expect(() => proto.getBindingAtIndex(10)).toThrowError('Index 10 is out-of-bounds.');
|
expect(() => proto.getProviderAtIndex(10)).toThrowError('Index 10 is out-of-bounds.');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('dynamic strategy', () => {
|
describe('dynamic strategy', () => {
|
||||||
it("should allow for direct access using getBindingAtIndex", () => {
|
it("should allow for direct access using getProviderAtIndex", () => {
|
||||||
var proto = createPei(null, 0, dynamicBindings);
|
var proto = createPei(null, 0, dynamicProviders);
|
||||||
|
|
||||||
expect(proto.getBindingAtIndex(0)).toBeAnInstanceOf(DirectiveBinding);
|
expect(proto.getProviderAtIndex(0)).toBeAnInstanceOf(DirectiveProvider);
|
||||||
expect(() => proto.getBindingAtIndex(-1)).toThrowError('Index -1 is out-of-bounds.');
|
expect(() => proto.getProviderAtIndex(-1)).toThrowError('Index -1 is out-of-bounds.');
|
||||||
expect(() => proto.getBindingAtIndex(dynamicBindings.length - 1)).not.toThrow();
|
expect(() => proto.getProviderAtIndex(dynamicProviders.length - 1)).not.toThrow();
|
||||||
expect(() => proto.getBindingAtIndex(dynamicBindings.length))
|
expect(() => proto.getProviderAtIndex(dynamicProviders.length))
|
||||||
.toThrowError(`Index ${dynamicBindings.length} is out-of-bounds.`);
|
.toThrowError(`Index ${dynamicProviders.length} is out-of-bounds.`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('event emitters', () => {
|
describe('event emitters', () => {
|
||||||
it('should return a list of event accessors', () => {
|
it('should return a list of event accessors', () => {
|
||||||
var binding = DirectiveBinding.createFromType(HasEventEmitter,
|
var provider = DirectiveProvider.createFromType(HasEventEmitter,
|
||||||
new DirectiveMetadata({outputs: ['emitter']}));
|
new DirectiveMetadata({outputs: ['emitter']}));
|
||||||
|
|
||||||
var inj = createPei(null, 0, [binding]);
|
var inj = createPei(null, 0, [provider]);
|
||||||
expect(inj.eventEmitterAccessors.length).toEqual(1);
|
expect(inj.eventEmitterAccessors.length).toEqual(1);
|
||||||
|
|
||||||
var accessor = inj.eventEmitterAccessors[0][0];
|
var accessor = inj.eventEmitterAccessors[0][0];
|
||||||
@ -356,10 +356,10 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should allow a different event vs field name', () => {
|
it('should allow a different event vs field name', () => {
|
||||||
var binding = DirectiveBinding.createFromType(HasEventEmitter,
|
var provider = DirectiveProvider.createFromType(HasEventEmitter,
|
||||||
new DirectiveMetadata({outputs: ['emitter: publicEmitter']}));
|
new DirectiveMetadata({outputs: ['emitter: publicEmitter']}));
|
||||||
|
|
||||||
var inj = createPei(null, 0, [binding]);
|
var inj = createPei(null, 0, [provider]);
|
||||||
expect(inj.eventEmitterAccessors.length).toEqual(1);
|
expect(inj.eventEmitterAccessors.length).toEqual(1);
|
||||||
|
|
||||||
var accessor = inj.eventEmitterAccessors[0][0];
|
var accessor = inj.eventEmitterAccessors[0][0];
|
||||||
@ -369,53 +369,53 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe(".create", () => {
|
describe(".create", () => {
|
||||||
it("should collect bindings from all directives", () => {
|
it("should collect providers from all directives", () => {
|
||||||
var pei = createPei(null, 0, [
|
var pei = createPei(null, 0, [
|
||||||
DirectiveBinding.createFromType(
|
DirectiveProvider.createFromType(
|
||||||
SimpleDirective,
|
SimpleDirective,
|
||||||
new ComponentMetadata({bindings: [bind('injectable1').toValue('injectable1')]})),
|
new ComponentMetadata({providers: [provide('injectable1', {asValue: 'injectable1'})]})),
|
||||||
DirectiveBinding.createFromType(SomeOtherDirective, new ComponentMetadata({
|
DirectiveProvider.createFromType(SomeOtherDirective, new ComponentMetadata({
|
||||||
bindings: [bind('injectable2').toValue('injectable2')]
|
providers: [provide('injectable2', {asValue: 'injectable2'})]
|
||||||
}))
|
}))
|
||||||
]);
|
]);
|
||||||
|
|
||||||
expect(pei.getBindingAtIndex(0).key.token).toBe(SimpleDirective);
|
expect(pei.getProviderAtIndex(0).key.token).toBe(SimpleDirective);
|
||||||
expect(pei.getBindingAtIndex(1).key.token).toBe(SomeOtherDirective);
|
expect(pei.getProviderAtIndex(1).key.token).toBe(SomeOtherDirective);
|
||||||
expect(pei.getBindingAtIndex(2).key.token).toEqual("injectable1");
|
expect(pei.getProviderAtIndex(2).key.token).toEqual("injectable1");
|
||||||
expect(pei.getBindingAtIndex(3).key.token).toEqual("injectable2");
|
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,
|
var pei = createPei(null, 0,
|
||||||
[DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata({
|
[DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata({
|
||||||
viewBindings: [bind('injectable1').toValue('injectable1')]
|
viewProviders: [provide('injectable1', {asValue: 'injectable1'})]
|
||||||
}))],
|
}))],
|
||||||
0, true);
|
0, true);
|
||||||
|
|
||||||
expect(pei.getBindingAtIndex(0).key.token).toBe(SimpleDirective);
|
expect(pei.getProviderAtIndex(0).key.token).toBe(SimpleDirective);
|
||||||
expect(pei.getBindingAtIndex(1).key.token).toEqual("injectable1");
|
expect(pei.getProviderAtIndex(1).key.token).toEqual("injectable1");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should flatten nested arrays", () => {
|
it("should flatten nested arrays", () => {
|
||||||
var pei = createPei(null, 0, [
|
var pei = createPei(null, 0, [
|
||||||
DirectiveBinding.createFromType(
|
DirectiveProvider.createFromType(
|
||||||
SimpleDirective,
|
SimpleDirective,
|
||||||
new ComponentMetadata({
|
new ComponentMetadata({
|
||||||
viewBindings: [[[bind('view').toValue('view')]]],
|
viewProviders: [[[provide('view', {asValue: 'view'})]]],
|
||||||
bindings: [[[bind('host').toValue('host')]]]
|
providers: [[[provide('host', {asValue: 'host'})]]]
|
||||||
}))
|
}))
|
||||||
], 0, true);
|
], 0, true);
|
||||||
|
|
||||||
expect(pei.getBindingAtIndex(0).key.token).toBe(SimpleDirective);
|
expect(pei.getProviderAtIndex(0).key.token).toBe(SimpleDirective);
|
||||||
expect(pei.getBindingAtIndex(1).key.token).toEqual("view");
|
expect(pei.getProviderAtIndex(1).key.token).toEqual("view");
|
||||||
expect(pei.getBindingAtIndex(2).key.token).toEqual("host");
|
expect(pei.getProviderAtIndex(2).key.token).toEqual("host");
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support an arbitrary number of bindings', () => {
|
it('should support an arbitrary number of providers', () => {
|
||||||
var pei = createPei(null, 0, dynamicBindings);
|
var pei = createPei(null, 0, dynamicProviders);
|
||||||
|
|
||||||
for (var i = 0; i < dynamicBindings.length; i++) {
|
for (var i = 0; i < dynamicProviders.length; i++) {
|
||||||
expect(pei.getBindingAtIndex(i).key.token).toBe(i);
|
expect(pei.getProviderAtIndex(i).key.token).toBe(i);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@ -463,7 +463,7 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("hasBindings", () => {
|
describe("hasBindings", () => {
|
||||||
it("should be true when there are bindings", () => {
|
it("should be true when there are providers", () => {
|
||||||
var p = createPei(null, 0, [SimpleDirective]);
|
var p = createPei(null, 0, [SimpleDirective]);
|
||||||
expect(p.hasBindings).toBeTruthy();
|
expect(p.hasBindings).toBeTruthy();
|
||||||
});
|
});
|
||||||
@ -482,22 +482,22 @@ export function main() {
|
|||||||
() => { expect(injector([SimpleDirective]).hasInstances()).toBe(true); });
|
() => { expect(injector([SimpleDirective]).hasInstances()).toBe(true); });
|
||||||
});
|
});
|
||||||
|
|
||||||
[{ strategy: 'inline', bindings: [] }, { strategy: 'dynamic',
|
[{ strategy: 'inline', providers: [] }, { strategy: 'dynamic',
|
||||||
bindings: dynamicBindings }].forEach((context) => {
|
providers: dynamicProviders }].forEach((context) => {
|
||||||
|
|
||||||
var extraBindings = context['bindings'];
|
var extraProviders = context['providers'];
|
||||||
describe(`${context['strategy']} strategy`, () => {
|
describe(`${context['strategy']} strategy`, () => {
|
||||||
|
|
||||||
describe("hydrate", () => {
|
describe("hydrate", () => {
|
||||||
it("should instantiate directives that have no dependencies", () => {
|
it("should instantiate directives that have no dependencies", () => {
|
||||||
var bindings = ListWrapper.concat([SimpleDirective], extraBindings);
|
var providers = ListWrapper.concat([SimpleDirective], extraProviders);
|
||||||
var inj = injector(bindings);
|
var inj = injector(providers);
|
||||||
expect(inj.get(SimpleDirective)).toBeAnInstanceOf(SimpleDirective);
|
expect(inj.get(SimpleDirective)).toBeAnInstanceOf(SimpleDirective);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should instantiate directives that depend on an arbitrary number of directives", () => {
|
it("should instantiate directives that depend on an arbitrary number of directives", () => {
|
||||||
var bindings = ListWrapper.concat([SimpleDirective, NeedsDirective], extraBindings);
|
var providers = ListWrapper.concat([SimpleDirective, NeedsDirective], extraProviders);
|
||||||
var inj = injector(bindings);
|
var inj = injector(providers);
|
||||||
|
|
||||||
var d = inj.get(NeedsDirective);
|
var d = inj.get(NeedsDirective);
|
||||||
|
|
||||||
@ -505,80 +505,74 @@ export function main() {
|
|||||||
expect(d.dependency).toBeAnInstanceOf(SimpleDirective);
|
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() {
|
function() {
|
||||||
var childInj = parentChildInjectors(
|
var childInj = parentChildInjectors(
|
||||||
ListWrapper.concat(
|
ListWrapper.concat(
|
||||||
[DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata({
|
[DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata({
|
||||||
bindings: [bind('injectable1').toValue('injectable1')]
|
providers: [provide('injectable1', {asValue: 'injectable1'})]
|
||||||
}))],
|
}))],
|
||||||
extraBindings),
|
extraProviders),
|
||||||
[DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata({
|
[DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata({
|
||||||
bindings: [
|
providers: [
|
||||||
bind('injectable1')
|
provide('injectable1', {asValue:'new-injectable1'}),
|
||||||
.toValue('new-injectable1'),
|
provide('injectable2', {asFactory:
|
||||||
bind('injectable2')
|
|
||||||
.toFactory(
|
|
||||||
(val) => `${val}-injectable2`,
|
(val) => `${val}-injectable2`,
|
||||||
[[new InjectMetadata('injectable1'), new SkipSelfMetadata()]])
|
deps: [[new InjectMetadata('injectable1'), new SkipSelfMetadata()]]})
|
||||||
]
|
]
|
||||||
}))]);
|
}))]);
|
||||||
expect(childInj.get('injectable2')).toEqual('injectable1-injectable2');
|
expect(childInj.get('injectable2')).toEqual('injectable1-injectable2');
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should instantiate bindings that have dependencies", () => {
|
it("should instantiate providers that have dependencies", () => {
|
||||||
var bindings = [
|
var providers = [
|
||||||
bind('injectable1')
|
provide('injectable1', {asValue: 'injectable1'}),
|
||||||
.toValue('injectable1'),
|
provide('injectable2', {asFactory:
|
||||||
bind('injectable2')
|
|
||||||
.toFactory(
|
|
||||||
(val) => `${val}-injectable2`,
|
(val) => `${val}-injectable2`,
|
||||||
['injectable1'])
|
deps: ['injectable1']})
|
||||||
];
|
];
|
||||||
|
|
||||||
var inj = injector(ListWrapper.concat(
|
var inj = injector(ListWrapper.concat(
|
||||||
[DirectiveBinding.createFromType(SimpleDirective,
|
[DirectiveProvider.createFromType(SimpleDirective,
|
||||||
new DirectiveMetadata({bindings: bindings}))],
|
new DirectiveMetadata({providers: providers}))],
|
||||||
extraBindings));
|
extraProviders));
|
||||||
|
|
||||||
expect(inj.get('injectable2')).toEqual('injectable1-injectable2');
|
expect(inj.get('injectable2')).toEqual('injectable1-injectable2');
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should instantiate viewBindings that have dependencies", () => {
|
it("should instantiate viewProviders that have dependencies", () => {
|
||||||
var viewBindings = [
|
var viewProviders = [
|
||||||
bind('injectable1')
|
provide('injectable1', {asValue: 'injectable1'}),
|
||||||
.toValue('injectable1'),
|
provide('injectable2', {asFactory:
|
||||||
bind('injectable2')
|
(val) => `${val}-injectable2`,
|
||||||
.toFactory(
|
deps: ['injectable1']})
|
||||||
(val) => `${val}-injectable2`,
|
|
||||||
['injectable1'])
|
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|
||||||
var inj = injector(ListWrapper.concat(
|
var inj = injector(ListWrapper.concat(
|
||||||
[DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata({
|
[DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata({
|
||||||
viewBindings: viewBindings}))], extraBindings),
|
viewProviders: viewProviders}))], extraProviders),
|
||||||
null, true);
|
null, true);
|
||||||
expect(inj.get('injectable2')).toEqual('injectable1-injectable2');
|
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(
|
var inj = injector(
|
||||||
ListWrapper.concat([DirectiveBinding.createFromType(NeedsService, new ComponentMetadata({
|
ListWrapper.concat([DirectiveProvider.createFromType(NeedsService, new ComponentMetadata({
|
||||||
viewBindings: [bind('service').toValue('service')]
|
viewProviders: [provide('service', {asValue: 'service'})]
|
||||||
}))],
|
}))],
|
||||||
extraBindings),
|
extraProviders),
|
||||||
null, true);
|
null, true);
|
||||||
expect(inj.get(NeedsService).service).toEqual('service');
|
expect(inj.get(NeedsService).service).toEqual('service');
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should instantiate bindings lazily", () => {
|
it("should instantiate providers lazily", () => {
|
||||||
var created = false;
|
var created = false;
|
||||||
var inj = injector(
|
var inj = injector(
|
||||||
ListWrapper.concat([DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata({
|
ListWrapper.concat([DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata({
|
||||||
bindings: [bind('service').toFactory(() => created = true)]
|
providers: [provide('service', {asFactory: () => created = true})]
|
||||||
}))],
|
}))],
|
||||||
extraBindings),
|
extraProviders),
|
||||||
null, true);
|
null, true);
|
||||||
|
|
||||||
expect(created).toBe(false);
|
expect(created).toBe(false);
|
||||||
@ -588,13 +582,13 @@ export function main() {
|
|||||||
expect(created).toBe(true);
|
expect(created).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should instantiate view bindings lazily", () => {
|
it("should instantiate view providers lazily", () => {
|
||||||
var created = false;
|
var created = false;
|
||||||
var inj = injector(
|
var inj = injector(
|
||||||
ListWrapper.concat([DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata({
|
ListWrapper.concat([DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata({
|
||||||
viewBindings: [bind('service').toFactory(() => created = true)]
|
viewProviders: [provide('service', {asFactory: () => created = true})]
|
||||||
}))],
|
}))],
|
||||||
extraBindings),
|
extraProviders),
|
||||||
null, true);
|
null, true);
|
||||||
|
|
||||||
expect(created).toBe(false);
|
expect(created).toBe(false);
|
||||||
@ -604,31 +598,31 @@ export function main() {
|
|||||||
expect(created).toBe(true);
|
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({
|
var directiveAnnotation = new ComponentMetadata({
|
||||||
viewBindings: ListWrapper.concat([bind("service").toValue("service")], extraBindings)
|
viewProviders: ListWrapper.concat([provide("service", {asValue: "service"})], extraProviders)
|
||||||
});
|
});
|
||||||
var componentDirective =
|
var componentDirective =
|
||||||
DirectiveBinding.createFromType(SimpleDirective, directiveAnnotation);
|
DirectiveProvider.createFromType(SimpleDirective, directiveAnnotation);
|
||||||
expect(() => { injector([componentDirective, NeedsService], null); })
|
expect(() => { injector([componentDirective, NeedsService], null); })
|
||||||
.toThrowError(containsRegexp(
|
.toThrowError(containsRegexp(
|
||||||
`No provider for service! (${stringify(NeedsService) } -> service)`));
|
`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(
|
var shadowInj = hostShadowInjectors(
|
||||||
ListWrapper.concat([DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata({
|
ListWrapper.concat([DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata({
|
||||||
bindings: [bind('service').toValue('hostService')]})
|
providers: [provide('service', {asValue: 'hostService'})]})
|
||||||
)], extraBindings),
|
)], extraProviders),
|
||||||
ListWrapper.concat([NeedsService], extraBindings)
|
ListWrapper.concat([NeedsService], extraProviders)
|
||||||
);
|
);
|
||||||
expect(shadowInj.get(NeedsService).service).toEqual('hostService');
|
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([
|
var imperativelyCreatedInjector = Injector.resolveAndCreate([
|
||||||
bind("service").toValue('appService')
|
provide("service", {asValue: 'appService'})
|
||||||
]);
|
]);
|
||||||
var inj = injector([NeedsService], imperativelyCreatedInjector);
|
var inj = injector([NeedsService], imperativelyCreatedInjector);
|
||||||
expect(inj.get(NeedsService).service).toEqual('appService');
|
expect(inj.get(NeedsService).service).toEqual('appService');
|
||||||
@ -636,81 +630,81 @@ export function main() {
|
|||||||
expect(() => injector([NeedsServiceFromHost], imperativelyCreatedInjector)).toThrowError();
|
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([
|
var imperativelyCreatedInjector = Injector.resolveAndCreate([
|
||||||
bind("service").toValue('appService')
|
provide("service", {asValue: 'appService'})
|
||||||
]);
|
]);
|
||||||
var inj = hostShadowInjectors([SimpleDirective], [NeedsService, NeedsServiceFromHost], imperativelyCreatedInjector);
|
var inj = hostShadowInjectors([SimpleDirective], [NeedsService, NeedsServiceFromHost], imperativelyCreatedInjector);
|
||||||
expect(inj.get(NeedsService).service).toEqual('appService');
|
expect(inj.get(NeedsService).service).toEqual('appService');
|
||||||
expect(inj.get(NeedsServiceFromHost).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([
|
var imperativelyCreatedInjector = Injector.resolveAndCreate([
|
||||||
bind("service").toValue('appService')
|
provide("service", {asValue: 'appService'})
|
||||||
]);
|
]);
|
||||||
var inj = parentChildInjectors([], [NeedsService, NeedsServiceFromHost], null, imperativelyCreatedInjector);
|
var inj = parentChildInjectors([], [NeedsService, NeedsServiceFromHost], null, imperativelyCreatedInjector);
|
||||||
expect(inj.get(NeedsService).service).toEqual('appService');
|
expect(inj.get(NeedsService).service).toEqual('appService');
|
||||||
expect(inj.get(NeedsServiceFromHost).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(
|
var inj = injector(
|
||||||
ListWrapper.concat([DirectiveBinding.createFromType(NeedsService, new ComponentMetadata({
|
ListWrapper.concat([DirectiveProvider.createFromType(NeedsService, new ComponentMetadata({
|
||||||
bindings: [bind('service').toValue('hostService')],
|
providers: [provide('service', {asValue: 'hostService'})],
|
||||||
viewBindings: [bind('service').toValue('viewService')]})
|
viewProviders: [provide('service', {asValue: 'viewService'})]})
|
||||||
)], extraBindings), null, true);
|
)], extraProviders), null, true);
|
||||||
expect(inj.get(NeedsService).service).toEqual('viewService');
|
expect(inj.get(NeedsService).service).toEqual('viewService');
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should prioritize directive bindings over component bindings", () => {
|
it("should prioritize directive providers over component providers", () => {
|
||||||
var component = DirectiveBinding.createFromType(NeedsService, new ComponentMetadata({
|
var component = DirectiveProvider.createFromType(NeedsService, new ComponentMetadata({
|
||||||
bindings: [bind('service').toValue('compService')]}));
|
providers: [provide('service', {asValue: 'compService'})]}));
|
||||||
var directive = DirectiveBinding.createFromType(SomeOtherDirective, new DirectiveMetadata({
|
var directive = DirectiveProvider.createFromType(SomeOtherDirective, new DirectiveMetadata({
|
||||||
bindings: [bind('service').toValue('dirService')]}));
|
providers: [provide('service', {asValue: 'dirService'})]}));
|
||||||
var inj = injector(ListWrapper.concat([component, directive], extraBindings), null, true);
|
var inj = injector(ListWrapper.concat([component, directive], extraProviders), null, true);
|
||||||
expect(inj.get(NeedsService).service).toEqual('dirService');
|
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", () => {
|
" of the component", () => {
|
||||||
expect(() => {
|
expect(() => {
|
||||||
hostShadowInjectors(
|
hostShadowInjectors(
|
||||||
ListWrapper.concat([
|
ListWrapper.concat([
|
||||||
DirectiveBinding.createFromType(SomeOtherDirective, new DirectiveMetadata({
|
DirectiveProvider.createFromType(SomeOtherDirective, new DirectiveMetadata({
|
||||||
bindings: [bind('service').toValue('hostService')]})
|
providers: [provide('service', {asValue: 'hostService'})]})
|
||||||
)], extraBindings),
|
)], extraProviders),
|
||||||
ListWrapper.concat([NeedsServiceFromHost], extraBindings)
|
ListWrapper.concat([NeedsServiceFromHost], extraProviders)
|
||||||
);
|
);
|
||||||
}).toThrowError(new RegExp("No provider for service!"));
|
}).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", () => {
|
" of a decorator directive", () => {
|
||||||
expect(() => {
|
expect(() => {
|
||||||
hostShadowInjectors(
|
hostShadowInjectors(
|
||||||
ListWrapper.concat([
|
ListWrapper.concat([
|
||||||
SimpleDirective,
|
SimpleDirective,
|
||||||
DirectiveBinding.createFromType(SomeOtherDirective, new DirectiveMetadata({
|
DirectiveProvider.createFromType(SomeOtherDirective, new DirectiveMetadata({
|
||||||
bindings: [bind('service').toValue('hostService')]})
|
providers: [provide('service', {asValue: 'hostService'})]})
|
||||||
)], extraBindings),
|
)], extraProviders),
|
||||||
|
|
||||||
ListWrapper.concat([NeedsServiceFromHost], extraBindings)
|
ListWrapper.concat([NeedsServiceFromHost], extraProviders)
|
||||||
);
|
);
|
||||||
}).toThrowError(new RegExp("No provider for service!"));
|
}).toThrowError(new RegExp("No provider for service!"));
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should instantiate directives that depend on pre built objects", () => {
|
it("should instantiate directives that depend on pre built objects", () => {
|
||||||
var templateRef = new TemplateRef_(<any>new SpyElementRef());
|
var templateRef = new TemplateRef_(<any>new SpyElementRef());
|
||||||
var bindings = ListWrapper.concat([NeedsTemplateRef], extraBindings);
|
var providers = ListWrapper.concat([NeedsTemplateRef], extraProviders);
|
||||||
var inj = injector(bindings, null, false, new PreBuiltObjects(null, null, null, templateRef));
|
var inj = injector(providers, null, false, new PreBuiltObjects(null, null, null, templateRef));
|
||||||
|
|
||||||
expect(inj.get(NeedsTemplateRef).templateRef).toEqual(templateRef);
|
expect(inj.get(NeedsTemplateRef).templateRef).toEqual(templateRef);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should get directives", () => {
|
it("should get directives", () => {
|
||||||
var child = hostShadowInjectors(
|
var child = hostShadowInjectors(
|
||||||
ListWrapper.concat([SomeOtherDirective, SimpleDirective], extraBindings),
|
ListWrapper.concat([SomeOtherDirective, SimpleDirective], extraProviders),
|
||||||
[NeedsDirectiveFromHostShadowDom]);
|
[NeedsDirectiveFromHostShadowDom]);
|
||||||
|
|
||||||
var d = child.get(NeedsDirectiveFromHostShadowDom);
|
var d = child.get(NeedsDirectiveFromHostShadowDom);
|
||||||
@ -720,7 +714,7 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should get directives from the host", () => {
|
it("should get directives from the host", () => {
|
||||||
var child = parentChildInjectors(ListWrapper.concat([SimpleDirective], extraBindings),
|
var child = parentChildInjectors(ListWrapper.concat([SimpleDirective], extraProviders),
|
||||||
[NeeedsDirectiveFromHost]);
|
[NeeedsDirectiveFromHost]);
|
||||||
|
|
||||||
var d = child.get(NeeedsDirectiveFromHost);
|
var d = child.get(NeeedsDirectiveFromHost);
|
||||||
@ -730,30 +724,30 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should throw when a dependency cannot be resolved", () => {
|
it("should throw when a dependency cannot be resolved", () => {
|
||||||
expect(() => injector(ListWrapper.concat([NeeedsDirectiveFromHost], extraBindings)))
|
expect(() => injector(ListWrapper.concat([NeeedsDirectiveFromHost], extraProviders)))
|
||||||
.toThrowError(containsRegexp(
|
.toThrowError(containsRegexp(
|
||||||
`No provider for ${stringify(SimpleDirective) }! (${stringify(NeeedsDirectiveFromHost) } -> ${stringify(SimpleDirective) })`));
|
`No provider for ${stringify(SimpleDirective) }! (${stringify(NeeedsDirectiveFromHost) } -> ${stringify(SimpleDirective) })`));
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should inject null when an optional dependency cannot be resolved", () => {
|
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);
|
var d = inj.get(OptionallyNeedsDirective);
|
||||||
expect(d.dependency).toEqual(null);
|
expect(d.dependency).toEqual(null);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should accept bindings instead of types", () => {
|
it("should accept providers instead of types", () => {
|
||||||
var inj = injector(
|
var inj = injector(
|
||||||
ListWrapper.concat([bind(SimpleDirective).toClass(SimpleDirective)], extraBindings));
|
ListWrapper.concat([provide(SimpleDirective, {asClass: SimpleDirective})], extraProviders));
|
||||||
expect(inj.get(SimpleDirective)).toBeAnInstanceOf(SimpleDirective);
|
expect(inj.get(SimpleDirective)).toBeAnInstanceOf(SimpleDirective);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should allow for direct access using getDirectiveAtIndex", () => {
|
it("should allow for direct access using getDirectiveAtIndex", () => {
|
||||||
var bindings =
|
var providers =
|
||||||
ListWrapper.concat([bind(SimpleDirective).toClass(SimpleDirective)], extraBindings);
|
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(0)).toBeAnInstanceOf(SimpleDirective);
|
||||||
expect(() => inj.getDirectiveAtIndex(-1)).toThrowError('Index -1 is out-of-bounds.');
|
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", () => {
|
it("should instantiate directives that depend on the containing component", () => {
|
||||||
var directiveBinding =
|
var directiveProvider =
|
||||||
DirectiveBinding.createFromType(SimpleDirective, new ComponentMetadata());
|
DirectiveProvider.createFromType(SimpleDirective, new ComponentMetadata());
|
||||||
var shadow = hostShadowInjectors(ListWrapper.concat([directiveBinding], extraBindings),
|
var shadow = hostShadowInjectors(ListWrapper.concat([directiveProvider], extraProviders),
|
||||||
[NeeedsDirectiveFromHost]);
|
[NeeedsDirectiveFromHost]);
|
||||||
|
|
||||||
var d = shadow.get(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",
|
it("should not instantiate directives that depend on other directives in the containing component's ElementInjector",
|
||||||
() => {
|
() => {
|
||||||
var directiveBinding =
|
var directiveProvider =
|
||||||
DirectiveBinding.createFromType(SomeOtherDirective, new ComponentMetadata());
|
DirectiveProvider.createFromType(SomeOtherDirective, new ComponentMetadata());
|
||||||
expect(() =>
|
expect(() =>
|
||||||
{
|
{
|
||||||
hostShadowInjectors(
|
hostShadowInjectors(
|
||||||
ListWrapper.concat([directiveBinding, SimpleDirective], extraBindings),
|
ListWrapper.concat([directiveProvider, SimpleDirective], extraProviders),
|
||||||
[NeedsDirective]);
|
[NeedsDirective]);
|
||||||
})
|
})
|
||||||
.toThrowError(containsRegexp(
|
.toThrowError(containsRegexp(
|
||||||
@ -789,12 +783,12 @@ export function main() {
|
|||||||
|
|
||||||
describe("getRootViewInjectors", () => {
|
describe("getRootViewInjectors", () => {
|
||||||
it("should return an empty array if there is no nested view", () => {
|
it("should return an empty array if there is no nested view", () => {
|
||||||
var inj = injector(extraBindings);
|
var inj = injector(extraProviders);
|
||||||
expect(inj.getRootViewInjectors()).toEqual([]);
|
expect(inj.getRootViewInjectors()).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return an empty array on a dehydrated view", () => {
|
it("should return an empty array on a dehydrated view", () => {
|
||||||
var inj = injector(extraBindings);
|
var inj = injector(extraProviders);
|
||||||
inj.dehydrate();
|
inj.dehydrate();
|
||||||
expect(inj.getRootViewInjectors()).toEqual([]);
|
expect(inj.getRootViewInjectors()).toEqual([]);
|
||||||
});
|
});
|
||||||
@ -810,19 +804,19 @@ export function main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
it("should handle repeated hydration / dehydration", () => {
|
it("should handle repeated hydration / dehydration", () => {
|
||||||
var inj = injector(extraBindings);
|
var inj = injector(extraProviders);
|
||||||
cycleHydrate(inj);
|
cycleHydrate(inj);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should handle repeated hydration / dehydration with query present", () => {
|
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);
|
cycleHydrate(inj);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
it("should handle repeated hydration / dehydration with view query present", () => {
|
it("should handle repeated hydration / dehydration with view query present", () => {
|
||||||
var inj = injector(extraBindings);
|
var inj = injector(extraProviders);
|
||||||
var host = injector(ListWrapper.concat([NeedsViewQuery], extraBindings));
|
var host = injector(ListWrapper.concat([NeedsViewQuery], extraProviders));
|
||||||
|
|
||||||
cycleHydrate(inj, host);
|
cycleHydrate(inj, host);
|
||||||
});
|
});
|
||||||
@ -831,9 +825,9 @@ export function main() {
|
|||||||
describe("lifecycle", () => {
|
describe("lifecycle", () => {
|
||||||
it("should call onDestroy on directives subscribed to this event", () => {
|
it("should call onDestroy on directives subscribed to this event", () => {
|
||||||
var inj = injector(ListWrapper.concat(
|
var inj = injector(ListWrapper.concat(
|
||||||
[DirectiveBinding.createFromType(DirectiveWithDestroy,
|
[DirectiveProvider.createFromType(DirectiveWithDestroy,
|
||||||
new DirectiveMetadata())],
|
new DirectiveMetadata())],
|
||||||
extraBindings));
|
extraProviders));
|
||||||
var destroy = inj.get(DirectiveWithDestroy);
|
var destroy = inj.get(DirectiveWithDestroy);
|
||||||
inj.dehydrate();
|
inj.dehydrate();
|
||||||
expect(destroy.onDestroyCounter).toBe(1);
|
expect(destroy.onDestroyCounter).toBe(1);
|
||||||
@ -841,9 +835,9 @@ export function main() {
|
|||||||
|
|
||||||
it("should work with services", () => {
|
it("should work with services", () => {
|
||||||
var inj = injector(ListWrapper.concat(
|
var inj = injector(ListWrapper.concat(
|
||||||
[DirectiveBinding.createFromType(
|
[DirectiveProvider.createFromType(
|
||||||
SimpleDirective, new DirectiveMetadata({bindings: [SimpleService]}))],
|
SimpleDirective, new DirectiveMetadata({providers: [SimpleService]}))],
|
||||||
extraBindings));
|
extraProviders));
|
||||||
inj.dehydrate();
|
inj.dehydrate();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@ -854,7 +848,7 @@ export function main() {
|
|||||||
attributes.set( 'type', 'text');
|
attributes.set( 'type', 'text');
|
||||||
attributes.set( 'title', '');
|
attributes.set( 'title', '');
|
||||||
|
|
||||||
var inj = injector(ListWrapper.concat([NeedsAttribute], extraBindings), null, false, null,
|
var inj = injector(ListWrapper.concat([NeedsAttribute], extraProviders), null, false, null,
|
||||||
attributes);
|
attributes);
|
||||||
var needsAttribute = inj.get(NeedsAttribute);
|
var needsAttribute = inj.get(NeedsAttribute);
|
||||||
|
|
||||||
@ -867,7 +861,7 @@ export function main() {
|
|||||||
var attributes = new Map();
|
var attributes = new Map();
|
||||||
attributes.set( 'foo', 'bar');
|
attributes.set( 'foo', 'bar');
|
||||||
|
|
||||||
var inj = injector(ListWrapper.concat([NeedsAttributeNoType], extraBindings), null, false,
|
var inj = injector(ListWrapper.concat([NeedsAttributeNoType], extraProviders), null, false,
|
||||||
null, attributes);
|
null, attributes);
|
||||||
var needsAttribute = inj.get(NeedsAttributeNoType);
|
var needsAttribute = inj.get(NeedsAttributeNoType);
|
||||||
|
|
||||||
@ -877,7 +871,7 @@ export function main() {
|
|||||||
|
|
||||||
describe("refs", () => {
|
describe("refs", () => {
|
||||||
it("should inject ElementRef", () => {
|
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);
|
expect(inj.get(NeedsElementRef).elementRef).toBe(defaultPreBuiltObjects.elementRef);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -886,8 +880,8 @@ export function main() {
|
|||||||
var view = <any>createDummyView();
|
var view = <any>createDummyView();
|
||||||
var childView = createDummyView(cd);
|
var childView = createDummyView(cd);
|
||||||
view.spy('getNestedView').andReturn(childView);
|
view.spy('getNestedView').andReturn(childView);
|
||||||
var binding = DirectiveBinding.createFromType(ComponentNeedsChangeDetectorRef, new ComponentMetadata());
|
var provider = DirectiveProvider.createFromType(ComponentNeedsChangeDetectorRef, new ComponentMetadata());
|
||||||
var inj = injector(ListWrapper.concat([binding], extraBindings), null, true,
|
var inj = injector(ListWrapper.concat([provider], extraProviders), null, true,
|
||||||
new PreBuiltObjects(null, view, <any>new SpyElementRef(), null));
|
new PreBuiltObjects(null, view, <any>new SpyElementRef(), null));
|
||||||
|
|
||||||
expect(inj.get(ComponentNeedsChangeDetectorRef).changeDetectorRef).toBe(cd.ref);
|
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", () => {
|
it("should inject ChangeDetectorRef of the containing component into directives", () => {
|
||||||
var cd = new DynamicChangeDetector(null, null, 0, [], [], null, [], [], [], null);
|
var cd = new DynamicChangeDetector(null, null, 0, [], [], null, [], [], [], null);
|
||||||
var view = createDummyView(cd);
|
var view = createDummyView(cd);
|
||||||
var binding = DirectiveBinding.createFromType(DirectiveNeedsChangeDetectorRef, new DirectiveMetadata());
|
var provider = DirectiveProvider.createFromType(DirectiveNeedsChangeDetectorRef, new DirectiveMetadata());
|
||||||
var inj = injector(ListWrapper.concat([binding], extraBindings), null, false,
|
var inj = injector(ListWrapper.concat([provider], extraProviders), null, false,
|
||||||
new PreBuiltObjects(null, view, <any>new SpyElementRef(), null));
|
new PreBuiltObjects(null, view, <any>new SpyElementRef(), null));
|
||||||
|
|
||||||
expect(inj.get(DirectiveNeedsChangeDetectorRef).changeDetectorRef).toBe(cd.ref);
|
expect(inj.get(DirectiveNeedsChangeDetectorRef).changeDetectorRef).toBe(cd.ref);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should inject ViewContainerRef', () => {
|
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_);
|
expect(inj.get(NeedsViewContainer).viewContainer).toBeAnInstanceOf(ViewContainerRef_);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should inject TemplateRef", () => {
|
it("should inject TemplateRef", () => {
|
||||||
var templateRef = new TemplateRef_(<any>new SpyElementRef());
|
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));
|
new PreBuiltObjects(null, null, null, templateRef));
|
||||||
|
|
||||||
expect(inj.get(NeedsTemplateRef).templateRef).toEqual(templateRef);
|
expect(inj.get(NeedsTemplateRef).templateRef).toEqual(templateRef);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should throw if there is no TemplateRef", () => {
|
it("should throw if there is no TemplateRef", () => {
|
||||||
expect(() => injector(ListWrapper.concat([NeedsTemplateRef], extraBindings)))
|
expect(() => injector(ListWrapper.concat([NeedsTemplateRef], extraProviders)))
|
||||||
.toThrowError(
|
.toThrowError(
|
||||||
`No provider for TemplateRef! (${stringify(NeedsTemplateRef) } -> TemplateRef)`);
|
`No provider for TemplateRef! (${stringify(NeedsTemplateRef) } -> TemplateRef)`);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should inject null if there is no TemplateRef when the dependency is optional', () => {
|
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);
|
var instance = inj.get(OptionallyInjectsTemplateRef);
|
||||||
expect(instance.templateRef).toBeNull();
|
expect(instance.templateRef).toBeNull();
|
||||||
});
|
});
|
||||||
@ -950,7 +944,7 @@ export function main() {
|
|||||||
|
|
||||||
it('should be injectable', () => {
|
it('should be injectable', () => {
|
||||||
var inj =
|
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);
|
expect(inj.get(NeedsQuery).query).toBeAnInstanceOf(QueryList);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -958,7 +952,7 @@ export function main() {
|
|||||||
var inj = injector(ListWrapper.concat([
|
var inj = injector(ListWrapper.concat([
|
||||||
NeedsQuery,
|
NeedsQuery,
|
||||||
CountingDirective
|
CountingDirective
|
||||||
], extraBindings), null,
|
], extraProviders), null,
|
||||||
false, preBuildObjects);
|
false, preBuildObjects);
|
||||||
|
|
||||||
addInj(dummyView, inj);
|
addInj(dummyView, inj);
|
||||||
@ -971,7 +965,7 @@ export function main() {
|
|||||||
var preBuiltObjects = new PreBuiltObjects(null, dummyView, null, new TemplateRef_(<any>new SpyElementRef()));
|
var preBuiltObjects = new PreBuiltObjects(null, dummyView, null, new TemplateRef_(<any>new SpyElementRef()));
|
||||||
var inj = injector(ListWrapper.concat([
|
var inj = injector(ListWrapper.concat([
|
||||||
NeedsTemplateRefQuery
|
NeedsTemplateRefQuery
|
||||||
], extraBindings), null,
|
], extraProviders), null,
|
||||||
false, preBuiltObjects);
|
false, preBuiltObjects);
|
||||||
addInj(dummyView, inj);
|
addInj(dummyView, inj);
|
||||||
|
|
||||||
@ -980,14 +974,14 @@ export function main() {
|
|||||||
expect(inj.get(NeedsTemplateRefQuery).query.first).toBe(preBuiltObjects.templateRef);
|
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 dirs = [NeedsQueryByVarBindings];
|
||||||
|
|
||||||
var dirVariableBindings = MapWrapper.createFromStringMap({
|
var dirVariableBindings = MapWrapper.createFromStringMap({
|
||||||
"one": null // element
|
"one": null // element
|
||||||
});
|
});
|
||||||
|
|
||||||
var inj = injector(dirs.concat(extraBindings), null,
|
var inj = injector(dirs.concat(extraProviders), null,
|
||||||
false, preBuildObjects, null, dirVariableBindings);
|
false, preBuildObjects, null, dirVariableBindings);
|
||||||
|
|
||||||
addInj(dummyView, inj);
|
addInj(dummyView, inj);
|
||||||
@ -996,8 +990,8 @@ export function main() {
|
|||||||
expect(inj.get(NeedsQueryByVarBindings).query.first).toBe(preBuildObjects.elementRef);
|
expect(inj.get(NeedsQueryByVarBindings).query.first).toBe(preBuildObjects.elementRef);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should contain directives on the same injector when querying by variable bindings' +
|
it('should contain directives on the same injector when querying by variable providers' +
|
||||||
'in the order of var bindings specified in the query', () => {
|
'in the order of var providers specified in the query', () => {
|
||||||
var dirs = [NeedsQueryByVarBindings, NeedsDirective, SimpleDirective];
|
var dirs = [NeedsQueryByVarBindings, NeedsDirective, SimpleDirective];
|
||||||
|
|
||||||
var dirVariableBindings = MapWrapper.createFromStringMap({
|
var dirVariableBindings = MapWrapper.createFromStringMap({
|
||||||
@ -1005,7 +999,7 @@ export function main() {
|
|||||||
"two": 1 // 1 is the index of NeedsDirective
|
"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);
|
false, preBuildObjects, null, dirVariableBindings);
|
||||||
|
|
||||||
addInj(dummyView, inj);
|
addInj(dummyView, inj);
|
||||||
@ -1019,7 +1013,7 @@ export function main() {
|
|||||||
it('should contain directives on the same and a child injector in construction order', () => {
|
it('should contain directives on the same and a child injector in construction order', () => {
|
||||||
var protoParent = createPei(null, 0, [NeedsQuery, CountingDirective]);
|
var protoParent = createPei(null, 0, [NeedsQuery, CountingDirective]);
|
||||||
var protoChild =
|
var protoChild =
|
||||||
createPei(protoParent, 1, ListWrapper.concat([CountingDirective], extraBindings));
|
createPei(protoParent, 1, ListWrapper.concat([CountingDirective], extraProviders));
|
||||||
|
|
||||||
var parent = protoParent.instantiate(null);
|
var parent = protoParent.instantiate(null);
|
||||||
var child = protoChild.instantiate(parent);
|
var child = protoChild.instantiate(parent);
|
||||||
|
@ -46,8 +46,9 @@ import {
|
|||||||
import {
|
import {
|
||||||
Injector,
|
Injector,
|
||||||
bind,
|
bind,
|
||||||
|
provide,
|
||||||
Injectable,
|
Injectable,
|
||||||
Binding,
|
Provider,
|
||||||
forwardRef,
|
forwardRef,
|
||||||
OpaqueToken,
|
OpaqueToken,
|
||||||
Inject,
|
Inject,
|
||||||
@ -96,7 +97,7 @@ const ANCHOR_ELEMENT = CONST_EXPR(new OpaqueToken('AnchorElement'));
|
|||||||
export function main() {
|
export function main() {
|
||||||
describe('integration tests', function() {
|
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() {
|
describe('react to record changes', function() {
|
||||||
it('should consume text node changes',
|
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) => {
|
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||||
tcb.overrideView(DirectiveProvidingInjectableInView, new ViewMetadata({
|
tcb.overrideView(DirectiveProvidingInjectableInView, new ViewMetadata({
|
||||||
template: `
|
template: `
|
||||||
@ -1515,8 +1516,8 @@ export function main() {
|
|||||||
|
|
||||||
describe('logging property updates', () => {
|
describe('logging property updates', () => {
|
||||||
beforeEachBindings(() => [
|
beforeEachBindings(() => [
|
||||||
bind(ChangeDetectorGenConfig)
|
provide(ChangeDetectorGenConfig,
|
||||||
.toValue(new ChangeDetectorGenConfig(true, true, true, false))
|
{asValue: new ChangeDetectorGenConfig(true, true, true, false)})
|
||||||
]);
|
]);
|
||||||
|
|
||||||
it('should reflect property values as attributes',
|
it('should reflect property values as attributes',
|
||||||
@ -1740,7 +1741,7 @@ class DynamicViewport {
|
|||||||
var myService = new MyService();
|
var myService = new MyService();
|
||||||
myService.greeting = 'dynamic greet';
|
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)
|
this.done = compiler.compileInHost(ChildCompUsingService)
|
||||||
.then((hostPv) => {vc.createHostView(hostPv, 0, bindings)});
|
.then((hostPv) => {vc.createHostView(hostPv, 0, bindings)});
|
||||||
}
|
}
|
||||||
@ -1841,7 +1842,7 @@ class MyComp {
|
|||||||
throwError() { throw 'boom'; }
|
throwError() { throw 'boom'; }
|
||||||
}
|
}
|
||||||
|
|
||||||
@Component({selector: 'child-cmp', inputs: ['dirProp'], viewBindings: [MyService]})
|
@Component({selector: 'child-cmp', inputs: ['dirProp'], viewProviders: [MyService]})
|
||||||
@View({directives: [MyDir], template: '{{ctxProp}}'})
|
@View({directives: [MyDir], template: '{{ctxProp}}'})
|
||||||
@Injectable()
|
@Injectable()
|
||||||
class ChildComp {
|
class ChildComp {
|
||||||
@ -1883,7 +1884,7 @@ class CompWithHost {
|
|||||||
constructor(@Host() someComp: SomeDirective) { this.myHost = someComp; }
|
constructor(@Host() someComp: SomeDirective) { this.myHost = someComp; }
|
||||||
}
|
}
|
||||||
|
|
||||||
@Component({selector: '[child-cmp2]', viewBindings: [MyService]})
|
@Component({selector: '[child-cmp2]', viewProviders: [MyService]})
|
||||||
@Injectable()
|
@Injectable()
|
||||||
class ChildComp2 {
|
class ChildComp2 {
|
||||||
ctxProp: string;
|
ctxProp: string;
|
||||||
@ -2025,7 +2026,7 @@ class PublicApi {
|
|||||||
|
|
||||||
@Directive({
|
@Directive({
|
||||||
selector: '[public-api]',
|
selector: '[public-api]',
|
||||||
bindings: [new Binding(PublicApi, {toAlias: PrivateImpl, deps: []})]
|
providers: [new Provider(PublicApi, {toAlias: PrivateImpl, deps: []})]
|
||||||
})
|
})
|
||||||
@Injectable()
|
@Injectable()
|
||||||
class PrivateImpl extends PublicApi {
|
class PrivateImpl extends PublicApi {
|
||||||
@ -2092,8 +2093,9 @@ function createInjectableWithLogging(inj: Injector) {
|
|||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'component-providing-logging-injectable',
|
selector: 'component-providing-logging-injectable',
|
||||||
bindings:
|
providers: [
|
||||||
[new Binding(InjectableService, {toFactory: createInjectableWithLogging, deps: [Injector]})]
|
new Provider(InjectableService, {toFactory: createInjectableWithLogging, deps: [Injector]})
|
||||||
|
]
|
||||||
})
|
})
|
||||||
@View({template: ''})
|
@View({template: ''})
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@ -2102,12 +2104,12 @@ class ComponentProvidingLoggingInjectable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Directive({selector: 'directive-providing-injectable', bindings: [[InjectableService]]})
|
@Directive({selector: 'directive-providing-injectable', providers: [[InjectableService]]})
|
||||||
@Injectable()
|
@Injectable()
|
||||||
class DirectiveProvidingInjectable {
|
class DirectiveProvidingInjectable {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Component({selector: 'directive-providing-injectable', viewBindings: [[InjectableService]]})
|
@Component({selector: 'directive-providing-injectable', viewProviders: [[InjectableService]]})
|
||||||
@View({template: ''})
|
@View({template: ''})
|
||||||
@Injectable()
|
@Injectable()
|
||||||
class DirectiveProvidingInjectableInView {
|
class DirectiveProvidingInjectableInView {
|
||||||
@ -2115,8 +2117,8 @@ class DirectiveProvidingInjectableInView {
|
|||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'directive-providing-injectable',
|
selector: 'directive-providing-injectable',
|
||||||
bindings: [new Binding(InjectableService, {toValue: 'host'})],
|
providers: [new Provider(InjectableService, {toValue: 'host'})],
|
||||||
viewBindings: [new Binding(InjectableService, {toValue: 'view'})]
|
viewProviders: [new Provider(InjectableService, {toValue: 'view'})]
|
||||||
})
|
})
|
||||||
@View({template: ''})
|
@View({template: ''})
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@ -2168,7 +2170,7 @@ class EventBus {
|
|||||||
|
|
||||||
@Directive({
|
@Directive({
|
||||||
selector: 'grand-parent-providing-event-bus',
|
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 {
|
class GrandParentProvidingEventBus {
|
||||||
bus: EventBus;
|
bus: EventBus;
|
||||||
@ -2182,9 +2184,9 @@ function createParentBus(peb) {
|
|||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'parent-providing-event-bus',
|
selector: 'parent-providing-event-bus',
|
||||||
bindings: [
|
providers: [
|
||||||
new Binding(EventBus,
|
new Provider(EventBus,
|
||||||
{toFactory: createParentBus, deps: [[EventBus, new SkipSelfMetadata()]]})
|
{toFactory: createParentBus, deps: [[EventBus, new SkipSelfMetadata()]]})
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
@View({
|
@View({
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user