feat(core): Add a long-form syntax for Angular bootstrapping.

This change adds a syntax for bootstrapping Angular on a page that allows more fine-grained control of the hierarchy created. platform() creates a platform injector (of which there can only be one). From the platform, .application() creates an Angular application including a Zone and all specified application bindings (e.g. for the DOM, HTTP, Compiler, Renderer, etc). At the application level, .bootstrap() will bootstrap the given component into that application.

Closes #3852
This commit is contained in:
Alex Rickabaugh
2015-09-14 23:37:39 +00:00
parent 193792c27f
commit 97d1844bfc
16 changed files with 503 additions and 408 deletions
+1 -1
View File
@@ -5,9 +5,9 @@ export 'package:angular2/src/core/util.dart';
export 'package:angular2/src/core/di.dart';
export 'package:angular2/src/core/pipes.dart';
export 'package:angular2/src/core/facade.dart';
export 'package:angular2/src/core/application_ref.dart';
// Do not export application for dart. Must import from angular2/bootstrap
//export 'package:angular2/src/core/application.dart';
export 'package:angular2/src/core/application_ref.dart';
export 'package:angular2/src/core/services.dart';
export 'package:angular2/src/core/compiler.dart';
export 'package:angular2/src/core/lifecycle.dart';
+3 -3
View File
@@ -6,9 +6,9 @@ import 'package:angular2/src/core/reflection/reflection.dart' show reflector;
import 'package:angular2/src/core/reflection/reflection_capabilities.dart'
show ReflectionCapabilities;
import 'application_common.dart';
import 'application_ref.dart';
export 'application_ref.dart' show ApplicationRef;
import 'package:angular2/src/core/compiler/dynamic_component_loader.dart';
export 'package:angular2/src/core/compiler/dynamic_component_loader.dart' show ComponentRef;
/// Starts an application from a root component. This implementation uses
/// mirrors. Angular 2 transformer automatically replaces this method with a
@@ -16,7 +16,7 @@ export 'application_ref.dart' show ApplicationRef;
/// mirrors and produces a faster and more compact JS code.
///
/// See [commonBootstrap] for detailed documentation.
Future<ApplicationRef> bootstrap(Type appComponentType,
Future<ComponentRef> bootstrap(Type appComponentType,
[List componentInjectableBindings]) {
reflector.reflectionCapabilities = new ReflectionCapabilities();
return commonBootstrap(appComponentType, componentInjectableBindings);
+2 -1
View File
@@ -1,3 +1,4 @@
// Public API for Application
export {ApplicationRef} from './application_ref';
export {APP_COMPONENT} from './application_tokens';
export {platform, commonBootstrap as bootstrap} from './application_common';
export {PlatformRef, ApplicationRef, rootBindings} from './application_ref';
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -2,12 +2,12 @@ library angular2.src.core.application_static;
import 'dart:async';
import 'application_common.dart';
import 'application_ref.dart';
import 'package:angular2/src/core/compiler/dynamic_component_loader.dart' show ComponentRef;
/// Starts an application from a root component.
///
/// See [commonBootstrap] for detailed documentation.
Future<ApplicationRef> bootstrapStatic(Type appComponentType,
Future<ComponentRef> bootstrapStatic(Type appComponentType,
[List componentInjectableBindings, void initReflector()]) {
if (initReflector != null) {
initReflector();
+2 -2
View File
@@ -2,7 +2,7 @@ library angular2.src.core.bootstrap;
import 'dart:async';
import 'application_ref.dart';
import 'package:angular2/src/core/compiler/dynamic_component_loader.dart' show ComponentRef;
import 'package:angular2/src/core/reflection/reflection.dart' show reflector;
import 'package:angular2/src/core/reflection/reflection_capabilities.dart'
show ReflectionCapabilities;
@@ -14,7 +14,7 @@ import 'application_common.dart';
/// mirrors and produces a faster and more compact JS code.
///
/// See [commonBootstrap] for detailed documentation.
Future<ApplicationRef> bootstrap(Type appComponentType,
Future<ComponentRef> bootstrap(Type appComponentType,
[List componentInjectableBindings]) {
reflector.reflectionCapabilities = new ReflectionCapabilities();
return commonBootstrap(appComponentType, componentInjectableBindings);
@@ -1,11 +1,15 @@
import {Key, Injector, ResolvedBinding, Binding, bind, Injectable} from 'angular2/src/core/di';
import {Compiler} from './compiler';
import {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 {AppViewManager} from 'angular2/src/core/compiler/view_manager';
import {ElementRef} from './element_ref';
import {ViewRef, HostViewRef} from './view_ref';
function _asType(typeOrBinding: Type | Binding): Type {
return isType(typeOrBinding) ? typeOrBinding : (<Binding>typeOrBinding).token;
}
/**
* Angular's reference to a component instance.
*
@@ -22,12 +26,20 @@ export class ComponentRef {
*/
instance: any;
componentType: Type;
injector: Injector;
/**
* @private
*/
constructor(location: ElementRef, instance: any, private _dispose: () => void) {
constructor(location: ElementRef, instance: any, componentType: Type, injector: Injector,
private _dispose: () => void) {
this.location = location;
this.instance = instance;
this.componentType = componentType;
this.injector = injector;
}
/**
@@ -35,6 +47,10 @@ export class ComponentRef {
*/
get hostView(): HostViewRef { return this.location.parentView; }
get hostComponentType(): Type { return this.componentType; }
get hostComponent(): any { return this.instance; }
/**
* Dispose of the component instance.
*/
@@ -104,8 +120,8 @@ export class DynamicComponentLoader {
* </my-app>
* ```
*/
loadAsRoot(typeOrBinding: Type | Binding, overrideSelector: string,
injector: Injector): Promise<ComponentRef> {
loadAsRoot(typeOrBinding: Type | Binding, overrideSelector: string, injector: Injector,
onDispose?: () => void): Promise<ComponentRef> {
return this._compiler.compileInHost(typeOrBinding)
.then(hostProtoViewRef => {
var hostViewRef =
@@ -113,8 +129,14 @@ export class DynamicComponentLoader {
var newLocation = this._viewManager.getHostElement(hostViewRef);
var component = this._viewManager.getComponent(newLocation);
var dispose = () => { this._viewManager.destroyRootHostView(hostViewRef); };
return new ComponentRef(newLocation, component, dispose);
var dispose = () => {
this._viewManager.destroyRootHostView(hostViewRef);
if (isPresent(onDispose)) {
onDispose();
}
};
return new ComponentRef(newLocation, component, _asType(typeOrBinding), injector,
dispose);
});
}
@@ -229,7 +251,7 @@ export class DynamicComponentLoader {
viewContainer.remove(index);
}
};
return new ComponentRef(newLocation, component, dispose);
return new ComponentRef(newLocation, component, _asType(typeOrBinding), null, dispose);
});
}
}
@@ -1,4 +1,4 @@
library testability.get_testability;
library testability.browser_testability;
import './testability.dart';
@@ -80,8 +80,14 @@ class PublicTestability implements _JsObjectProxyable {
}
}
class GetTestability {
static addToWindow(TestabilityRegistry registry) {
class BrowserGetTestability implements GetTestability {
const BrowserGetTestability();
static init() {
setTestabilityGetter(const BrowserGetTestability());
}
void addToWindow(TestabilityRegistry registry) {
var jsRegistry = js.context['ngTestabilityRegistries'];
if (jsRegistry == null) {
js.context['ngTestabilityRegistries'] = jsRegistry = new js.JsArray();
@@ -106,10 +112,10 @@ class GetTestability {
return _jsify(result);
});
}
jsRegistry.add(_createRegistry(registry));
jsRegistry.add(this._createRegistry(registry));
}
static js.JsObject _createRegistry(TestabilityRegistry registry) {
js.JsObject _createRegistry(TestabilityRegistry registry) {
var object = new js.JsObject(js.context['Object']);
object['getAngularTestability'] = _jsify((Element elem,
bool findInAncestors) {
@@ -1,4 +1,9 @@
import {TestabilityRegistry, Testability} from 'angular2/src/core/testability/testability';
import {
TestabilityRegistry,
Testability,
GetTestability,
setTestabilityGetter
} from 'angular2/src/core/testability/testability';
import {global} from 'angular2/src/core/facade/lang';
class PublicTestability {
@@ -13,8 +18,10 @@ class PublicTestability {
}
}
export class GetTestability {
static addToWindow(registry: TestabilityRegistry) {
export class BrowserGetTestability implements GetTestability {
static init() { setTestabilityGetter(new BrowserGetTestability()); }
addToWindow(registry: TestabilityRegistry): void {
global.getAngularTestability = function(elem: Element, findInAncestors: boolean = true):
PublicTestability {
var testability = registry.findTestabilityInTree(elem, findInAncestors);
@@ -1,8 +1,8 @@
import {Injectable} from 'angular2/src/core/di';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {Map, MapWrapper, ListWrapper} from 'angular2/src/core/facade/collection';
import {CONST, CONST_EXPR} from 'angular2/src/core/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/core/facade/exceptions';
import * as getTestabilityModule from './get_testability';
import {NgZone} from '../zone/ng_zone';
import {PromiseWrapper} from 'angular2/src/core/facade/async';
@@ -76,7 +76,7 @@ export class Testability {
export class TestabilityRegistry {
_applications: Map<any, Testability> = new Map();
constructor() { getTestabilityModule.GetTestability.addToWindow(this); }
constructor() { testabilityGetter.addToWindow(this); }
registerApplication(token: any, testability: Testability) {
this._applications.set(token, testability);
@@ -99,3 +99,16 @@ export class TestabilityRegistry {
return this.findTestabilityInTree(DOM.parentElement(elem));
}
}
export interface GetTestability { addToWindow(registry: TestabilityRegistry): void; }
@CONST()
class NoopGetTestability implements GetTestability {
addToWindow(registry: TestabilityRegistry): void {}
}
export function setTestabilityGetter(getter: GetTestability): void {
testabilityGetter = getter;
}
var testabilityGetter: GetTestability = CONST_EXPR(new NoopGetTestability());
+1 -1
View File
@@ -7,7 +7,7 @@
import {createInjector} from "./di_bindings";
import {MessageBus, MessageBusSink} from "angular2/src/web_workers/shared/message_bus";
import {createNgZone} from 'angular2/src/core/application_common';
import {createNgZone} from 'angular2/src/core/application_ref';
import {Injectable} from 'angular2/src/core/di';
import {BrowserDomAdapter} from 'angular2/src/core/dom/browser_adapter';
import {wtfInit} from 'angular2/src/core/profile/wtf_init';
@@ -4,8 +4,8 @@ import "package:angular2/src/web_workers/shared/isolate_message_bus.dart";
import "package:angular2/src/web_workers/worker/application_common.dart"
show bootstrapWebWorkerCommon;
import "package:angular2/src/core/facade/async.dart" show Future;
import "package:angular2/src/core/application_ref.dart" show ApplicationRef;
import "package:angular2/src/core/facade/lang.dart" show Type, BaseException;
import "package:angular2/src/core/compiler/dynamic_component_loader.dart" show ComponentRef;
import "dart:isolate";
import "dart:async";
import 'dart:core';
@@ -21,7 +21,7 @@ import 'dart:core';
* bootstrap() in a regular Angular application
* See the bootstrap() docs for more details.
*/
Future<ApplicationRef> bootstrapWebWorker(
Future<ComponentRef> bootstrapWebWorker(
SendPort replyTo, Type appComponentType,
[List<dynamic> componentInjectableBindings = null]) {
ReceivePort rPort = new ReceivePort();
@@ -8,7 +8,7 @@ import {Binding, Injectable} from "angular2/src/core/di";
import {Map} from 'angular2/src/core/facade/collection';
import {Promise} from 'angular2/src/core/facade/async';
import {bootstrapWebWorkerCommon} from "angular2/src/web_workers/worker/application_common";
import {ApplicationRef} from "angular2/src/core/application_ref";
import {ComponentRef} from "angular2/src/core/compiler/dynamic_component_loader";
export * from "angular2/src/web_workers/shared/message_bus";
// TODO(jteplitz602) remove this and compile with lib.webworker.d.ts (#3492)
@@ -28,7 +28,7 @@ var _postMessage: PostMessageInterface = <any>postMessage;
*/
export function bootstrapWebWorker(
appComponentType: Type, componentInjectableBindings: Array<Type | Binding | any[]> = null):
Promise<ApplicationRef> {
Promise<ComponentRef> {
var sink = new PostMessageBusSink({
postMessage: (message: any, transferrables?:[ArrayBuffer]) => {
console.log("Sending", message);
@@ -1,5 +1,4 @@
import {Injector, bind, OpaqueToken, Binding} from 'angular2/src/core/di';
import {DEFAULT_PIPES} from 'angular2/src/core/pipes';
import {FORM_BINDINGS} from 'angular2/src/core/forms';
import {
NumberWrapper,
@@ -10,50 +9,21 @@ import {
print,
stringify
} from 'angular2/src/core/facade/lang';
import {Compiler, CompilerCache} from 'angular2/src/core/compiler/compiler';
import {Reflector, reflector} from 'angular2/src/core/reflection/reflection';
import {
Parser,
Lexer,
ChangeDetection,
DynamicChangeDetection,
JitChangeDetection,
PreGeneratedChangeDetection,
IterableDiffers,
defaultIterableDiffers,
KeyValueDiffers,
defaultKeyValueDiffers
} from 'angular2/src/core/change_detection/change_detection';
import {ExceptionHandler} from 'angular2/src/core/facade/exceptions';
import {DirectiveResolver} from 'angular2/src/core/compiler/directive_resolver';
import {StyleUrlResolver} from 'angular2/src/core/render/dom/compiler/style_url_resolver';
import {PipeResolver} from 'angular2/src/core/compiler/pipe_resolver';
import {ViewResolver} from 'angular2/src/core/compiler/view_resolver';
import {ListWrapper} from 'angular2/src/core/facade/collection';
import {Promise, PromiseWrapper, PromiseCompleter} from 'angular2/src/core/facade/async';
import {NgZone} from 'angular2/src/core/zone/ng_zone';
import {LifeCycle} from 'angular2/src/core/life_cycle/life_cycle';
import {XHR} from 'angular2/src/core/render/xhr';
import {WebWorkerXHRImpl} from 'angular2/src/web_workers/worker/xhr_impl';
import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper';
import {UrlResolver} from 'angular2/src/core/services/url_resolver';
import {AppRootUrl} from 'angular2/src/core/services/app_root_url';
import {
ComponentRef,
DynamicComponentLoader
} from 'angular2/src/core/compiler/dynamic_component_loader';
import {AppViewPool, APP_VIEW_POOL_CAPACITY} from 'angular2/src/core/compiler/view_pool';
import {AppViewManager} from 'angular2/src/core/compiler/view_manager';
import {AppViewManagerUtils} from 'angular2/src/core/compiler/view_manager_utils';
import {AppViewListener} from 'angular2/src/core/compiler/view_listener';
import {ProtoViewFactory} from 'angular2/src/core/compiler/proto_view_factory';
import {WebWorkerRenderer, WebWorkerCompiler} from './renderer';
import {Renderer, RenderCompiler} from 'angular2/src/core/render/api';
import {internalView} from 'angular2/src/core/compiler/view_ref';
import {ClientMessageBrokerFactory} from 'angular2/src/web_workers/shared/client_message_broker';
import {MessageBus} from 'angular2/src/web_workers/shared/message_bus';
import {APP_COMPONENT_REF_PROMISE, APP_COMPONENT} from 'angular2/src/core/application_tokens';
import {ApplicationRef} from 'angular2/src/core/application_ref';
import {
platformCommon,
PlatformRef,
ApplicationRef,
applicationCommonBindings
} from 'angular2/src/core/application_ref';
import {Serializer} from "angular2/src/web_workers/shared/serializer";
import {ON_WEB_WORKER} from "angular2/src/web_workers/shared/api";
import {RenderProtoViewRefStore} from 'angular2/src/web_workers/shared/render_proto_view_ref_store';
@@ -63,11 +33,12 @@ import {
import {ObservableWrapper} from 'angular2/src/core/facade/async';
import {SETUP_CHANNEL} from 'angular2/src/web_workers/shared/messaging_api';
import {WebWorkerEventDispatcher} from 'angular2/src/web_workers/worker/event_dispatcher';
import {ComponentRef} from 'angular2/src/core/compiler/dynamic_component_loader';
import {NgZone} from 'angular2/src/core/zone/ng_zone';
var _rootInjector: Injector;
// Contains everything that is safe to share between applications.
var _rootBindings = [bind(Reflector).toValue(reflector)];
export function platform(bindings?: Array<Type | Binding | any[]>): PlatformRef {
return platformCommon(bindings);
}
class PrintLogger {
log = print;
@@ -76,29 +47,9 @@ class PrintLogger {
logGroupEnd() {}
}
function _injectorBindings(appComponentType, bus: MessageBus, initData: StringMap<string, any>):
function webWorkerBindings(appComponentType, bus: MessageBus, initData: StringMap<string, any>):
Array<Type | Binding | any[]> {
var bestChangeDetection = new DynamicChangeDetection();
if (PreGeneratedChangeDetection.isSupported()) {
bestChangeDetection = new PreGeneratedChangeDetection();
} else if (JitChangeDetection.isSupported()) {
bestChangeDetection = new JitChangeDetection();
}
return [
bind(APP_COMPONENT)
.toValue(appComponentType),
bind(APP_COMPONENT_REF_PROMISE)
.toFactory(
(dynamicComponentLoader, injector) => {
// TODO(rado): investigate whether to support bindings on root component.
return dynamicComponentLoader.loadAsRoot(appComponentType, null, injector)
.then((componentRef) => { return componentRef; });
},
[DynamicComponentLoader, Injector]),
bind(appComponentType).toFactory((ref) => ref.instance, [APP_COMPONENT_REF_PROMISE]),
bind(LifeCycle).toFactory((exceptionHandler) => new LifeCycle(null, assertionsEnabled()),
[ExceptionHandler]),
Serializer,
bind(MessageBus).toValue(bus),
ClientMessageBrokerFactory,
@@ -109,93 +60,40 @@ function _injectorBindings(appComponentType, bus: MessageBus, initData: StringMa
bind(ON_WEB_WORKER).toValue(true),
RenderViewWithFragmentsStore,
RenderProtoViewRefStore,
ProtoViewFactory,
AppViewPool,
bind(APP_VIEW_POOL_CAPACITY).toValue(10000),
AppViewManager,
AppViewManagerUtils,
AppViewListener,
Compiler,
CompilerCache,
ViewResolver,
DEFAULT_PIPES,
bind(IterableDiffers).toValue(defaultIterableDiffers),
bind(KeyValueDiffers).toValue(defaultKeyValueDiffers),
bind(ChangeDetection).toValue(bestChangeDetection),
DirectiveResolver,
UrlResolver,
StyleUrlResolver,
PipeResolver,
Parser,
Lexer,
bind(ExceptionHandler).toFactory(() => new ExceptionHandler(new PrintLogger()), []),
WebWorkerXHRImpl,
bind(XHR).toAlias(WebWorkerXHRImpl),
ComponentUrlMapper,
DynamicComponentLoader,
bind(AppRootUrl).toValue(new AppRootUrl(initData['rootUrl'])),
WebWorkerEventDispatcher,
FORM_BINDINGS
];
}
export function bootstrapWebWorkerCommon(
appComponentType: Type, bus: MessageBus,
componentInjectableBindings: Array<Type | Binding | any[]> = null): Promise<ApplicationRef> {
export function bootstrapWebWorkerCommon(appComponentType: Type, bus: MessageBus,
appBindings: Array<Type | Binding | any[]> = null):
Promise<ComponentRef> {
var bootstrapProcess: PromiseCompleter<any> = PromiseWrapper.completer();
var appPromise = platform().asyncApplication((zone: NgZone) => {
// TODO(rado): prepopulate template cache, so applications with only
// index.html and main.js are possible.
//
bus.attachToZone(zone);
bus.initChannel(SETUP_CHANNEL, false);
var zone = new NgZone({enableLongStackTrace: assertionsEnabled()});
bus.attachToZone(zone);
var subscription: any;
bus.initChannel(SETUP_CHANNEL, false);
var emitter = bus.from(SETUP_CHANNEL);
subscription = ObservableWrapper.subscribe(emitter, (message: StringMap<string, any>) => {
zone.run(() => {
var exceptionHandler;
try {
var appInjector =
_createAppInjector(appComponentType, componentInjectableBindings, zone, bus, message);
exceptionHandler = appInjector.get(ExceptionHandler);
zone.overrideOnErrorHandler((e, s) => exceptionHandler.call(e, s));
var compRefToken: Promise<any> = appInjector.get(APP_COMPONENT_REF_PROMISE);
var tick = (componentRef) => {
var appChangeDetector = internalView(componentRef.hostView).changeDetector;
// retrieve life cycle: may have already been created if injected in root component
var lc = appInjector.get(LifeCycle);
lc.registerWith(zone, appChangeDetector);
lc.tick(); // the first tick that will bootstrap the app
bootstrapProcess.resolve(new ApplicationRef(componentRef, appComponentType, appInjector));
};
var tickResult = PromiseWrapper.then(compRefToken, tick);
PromiseWrapper.then(tickResult,
(_) => {}); // required for Dart to trigger the default error handler
PromiseWrapper.then(tickResult, null,
(err, stackTrace) => { bootstrapProcess.reject(err, stackTrace); });
ObservableWrapper.dispose(subscription);
} catch (e) {
if (isPresent(exceptionHandler)) {
exceptionHandler.call(e, e.stack);
}
bootstrapProcess.reject(e, e.stack);
var subscription: any;
var emitter = bus.from(SETUP_CHANNEL);
subscription = ObservableWrapper.subscribe(emitter, (message: StringMap<string, any>) => {
var bindings =
[applicationCommonBindings(), webWorkerBindings(appComponentType, bus, message)];
if (isPresent(appBindings)) {
bindings.push(appBindings);
}
bootstrapProcess.resolve(bindings);
ObservableWrapper.dispose(subscription);
});
ObservableWrapper.callNext(bus.to(SETUP_CHANNEL), "ready");
return bootstrapProcess.promise;
});
ObservableWrapper.callNext(bus.to(SETUP_CHANNEL), "ready");
return bootstrapProcess.promise;
}
function _createAppInjector(appComponentType: Type, bindings: Array<Type | Binding | any[]>,
zone: NgZone, bus: MessageBus, initData: StringMap<string, any>):
Injector {
if (isBlank(_rootInjector)) _rootInjector = Injector.resolveAndCreate(_rootBindings);
var mergedBindings: any[] =
isPresent(bindings) ?
ListWrapper.concat(_injectorBindings(appComponentType, bus, initData), bindings) :
_injectorBindings(appComponentType, bus, initData);
mergedBindings.push(bind(NgZone).toValue(zone));
return _rootInjector.resolveAndCreateChild(mergedBindings);
return PromiseWrapper.then(appPromise, (app) => app.bootstrap(appComponentType));
}
@@ -12,12 +12,12 @@ import {
} from 'angular2/test_lib';
import {isPresent, stringify} from 'angular2/src/core/facade/lang';
import {bootstrap} from 'angular2/bootstrap';
import {Component, Directive, View} from 'angular2/src/core/metadata';
import {ApplicationRef} from 'angular2/src/core/application_ref';
import {Component, Directive, View} from 'angular2/core';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {DOCUMENT} from 'angular2/render';
import {PromiseWrapper} from 'angular2/src/core/facade/async';
import {bind, Inject, Injector, LifeCycle} from 'angular2/core';
import {ApplicationRef} from 'angular2/src/core/application_ref';
import {ExceptionHandler} from 'angular2/src/core/facade/exceptions';
import {Testability, TestabilityRegistry} from 'angular2/src/core/testability/testability';
import {IS_DART} from '../platform';