this._zone.run(function () {
     var componentProviders = _componentProviders(componentType);
     if (lang_1.isPresent(providers)) {
         componentProviders.push(providers);
     }
     var exceptionHandler = _this._injector.get(exceptions_1.ExceptionHandler);
     _this._rootComponentTypes.push(componentType);
     try {
         var injector = _this._injector.resolveAndCreateChild(componentProviders);
         var compRefToken = injector.get(application_tokens_1.APP_COMPONENT_REF_PROMISE);
         var tick = function (componentRef) {
             var appChangeDetector = view_ref_1.internalView(componentRef.hostView).changeDetector;
             var lc = injector.get(life_cycle_1.LifeCycle);
             lc.registerWith(_this._zone, appChangeDetector);
             lc.tick();
             completer.resolve(componentRef);
             _this._rootComponents.push(componentRef);
             _this._bootstrapListeners.forEach(function (listener) { return listener(componentRef); });
         };
         var tickResult = async_1.PromiseWrapper.then(compRefToken, tick);
         async_1.PromiseWrapper.then(tickResult, function (_) { });
         async_1.PromiseWrapper.then(tickResult, null, function (err, stackTrace) { return completer.reject(err, stackTrace); });
     }
     catch (e) {
         exceptionHandler.call(e, e.stack);
         completer.reject(e, e.stack);
     }
 });
 normalizeDirectiveMetadata(directive) {
     if (!directive.isComponent) {
         // For non components there is nothing to be normalized yet.
         return PromiseWrapper.resolve(directive);
     }
     var normalizedTemplatePromise;
     if (directive.isComponent) {
         normalizedTemplatePromise =
             this._templateNormalizer.normalizeTemplate(directive.type, directive.template);
     }
     else {
         normalizedTemplatePromise = PromiseWrapper.resolve(null);
     }
     return normalizedTemplatePromise.then((normalizedTemplate) => new CompileDirectiveMetadata({
         type: directive.type,
         isComponent: directive.isComponent,
         dynamicLoadable: directive.dynamicLoadable,
         selector: directive.selector,
         exportAs: directive.exportAs,
         changeDetection: directive.changeDetection,
         inputs: directive.inputs,
         outputs: directive.outputs,
         hostListeners: directive.hostListeners,
         hostProperties: directive.hostProperties,
         hostAttributes: directive.hostAttributes,
         lifecycleHooks: directive.lifecycleHooks, template: normalizedTemplate
     }));
 }
Beispiel #3
0
 this._zone.run(() => {
     var componentProviders = _componentProviders(componentType);
     if (isPresent(providers)) {
         componentProviders.push(providers);
     }
     var exceptionHandler = this._injector.get(ExceptionHandler);
     this._rootComponentTypes.push(componentType);
     try {
         var injector = this._injector.resolveAndCreateChild(componentProviders);
         var compRefToken = injector.get(APP_COMPONENT_REF_PROMISE);
         var tick = (componentRef) => {
             var appChangeDetector = internalView(componentRef.hostView).changeDetector;
             var lc = injector.get(LifeCycle);
             lc.registerWith(this._zone, appChangeDetector);
             lc.tick();
             completer.resolve(componentRef);
             this._rootComponents.push(componentRef);
             this._bootstrapListeners.forEach((listener) => listener(componentRef));
         };
         var tickResult = PromiseWrapper.then(compRefToken, tick);
         PromiseWrapper.then(tickResult, (_) => { });
         PromiseWrapper.then(tickResult, null, (err, stackTrace) => completer.reject(err, stackTrace));
     }
     catch (e) {
         exceptionHandler.call(e, e.stack);
         completer.reject(e, e.stack);
     }
 });
 RouteRegistry.prototype._completeAuxiliaryRouteMatches = function (instruction, parentComponent) {
     var _this = this;
     if (lang_1.isBlank(instruction)) {
         return _resolveToNull;
     }
     var componentRecognizer = this._rules.get(parentComponent);
     var auxInstructions = {};
     var promises = instruction.auxUrls.map(function (auxSegment) {
         var match = componentRecognizer.recognizeAuxiliary(auxSegment);
         if (lang_1.isBlank(match)) {
             return _resolveToNull;
         }
         return _this._completePrimaryRouteMatch(match).then(function (auxInstruction) {
             if (lang_1.isPresent(auxInstruction)) {
                 return _this._completeAuxiliaryRouteMatches(auxInstruction, parentComponent)
                     .then(function (finishedAuxRoute) {
                     auxInstructions[auxSegment.path] = finishedAuxRoute;
                 });
             }
         });
     });
     return async_1.PromiseWrapper.all(promises).then(function (_) {
         if (lang_1.isBlank(instruction.child)) {
             return new instruction_1.Instruction(instruction.component, null, auxInstructions);
         }
         return _this._completeAuxiliaryRouteMatches(instruction.child, instruction.component.componentType)
             .then(function (completeChild) {
             return new instruction_1.Instruction(instruction.component, completeChild, auxInstructions);
         });
     });
 };
 constructor(componentType, data) {
     this.componentType = componentType;
     this.data = data;
     /** @internal */
     this._resolvedComponent = null;
     this._resolvedComponent = PromiseWrapper.resolve(componentType);
 }
 _compileComponentRuntime(cacheKey, compMeta, viewDirectives, compilingComponentCacheKeys) {
     var compiledTemplate = this._compiledTemplateCache.get(cacheKey);
     var done = this._compiledTemplateDone.get(cacheKey);
     if (isBlank(compiledTemplate)) {
         var styles;
         var changeDetectorFactory;
         var commands;
         var templateId = nextTemplateId();
         compiledTemplate =
             new CompiledTemplate(templateId, (_a, _b) => [changeDetectorFactory, commands, styles]);
         this._compiledTemplateCache.set(cacheKey, compiledTemplate);
         compilingComponentCacheKeys.add(cacheKey);
         done =
             PromiseWrapper.all([
                 this._styleCompiler.compileComponentRuntime(this._appId, templateId, compMeta.template)
             ].concat(viewDirectives.map(dirMeta => this.normalizeDirectiveMetadata(dirMeta))))
                 .then((stylesAndNormalizedViewDirMetas) => {
                 var childPromises = [];
                 var normalizedViewDirMetas = stylesAndNormalizedViewDirMetas.slice(1);
                 var parsedTemplate = this._templateParser.parse(compMeta.template.template, normalizedViewDirMetas, compMeta.type.name);
                 var changeDetectorFactories = this._cdCompiler.compileComponentRuntime(compMeta.type, compMeta.changeDetection, parsedTemplate);
                 changeDetectorFactory = changeDetectorFactories[0];
                 styles = stylesAndNormalizedViewDirMetas[0];
                 commands = this._compileCommandsRuntime(compMeta, templateId, parsedTemplate, changeDetectorFactories, compilingComponentCacheKeys, childPromises);
                 return PromiseWrapper.all(childPromises);
             })
                 .then((_) => {
                 SetWrapper.delete(compilingComponentCacheKeys, cacheKey);
                 return compiledTemplate;
             });
         this._compiledTemplateDone.set(cacheKey, done);
     }
     return compiledTemplate;
 }
Beispiel #7
0
 /**
  * Called by the {@link Router} during recognition phase of a navigation.
  *
  * If this resolves to `false`, the given navigation is cancelled.
  *
  * This method delegates to the child component's `canDeactivate` hook if it exists,
  * and otherwise resolves to true.
  */
 canDeactivate(nextInstruction) {
     if (isBlank(this._currentInstruction)) {
         return _resolveToTrue;
     }
     if (hasLifecycleHook(hookMod.canDeactivate, this._currentInstruction.componentType)) {
         return PromiseWrapper.resolve(this._componentRef.instance.canDeactivate(nextInstruction, this._currentInstruction));
     }
     return _resolveToTrue;
 }
 RouterOutlet.prototype.canDeactivate = function (nextInstruction) {
     if (lang_1.isBlank(this._currentInstruction)) {
         return _resolveToTrue;
     }
     if (route_lifecycle_reflector_1.hasLifecycleHook(hookMod.canDeactivate, this._currentInstruction.componentType)) {
         return async_1.PromiseWrapper.resolve(this._componentRef.instance.canDeactivate(nextInstruction, this._currentInstruction));
     }
     return _resolveToTrue;
 };
Beispiel #9
0
 /**
  * Called by the {@link Router} during the commit phase of a navigation when an outlet
  * reuses a component between different routes.
  * This method in turn is responsible for calling the `onReuse` hook of its child.
  */
 reuse(nextInstruction) {
     var previousInstruction = this._currentInstruction;
     this._currentInstruction = nextInstruction;
     if (isBlank(this._componentRef)) {
         throw new BaseException(`Cannot reuse an outlet that does not contain a component.`);
     }
     return PromiseWrapper.resolve(hasLifecycleHook(hookMod.onReuse, this._currentInstruction.componentType) ?
         this._componentRef.instance.onReuse(nextInstruction, previousInstruction) :
         true);
 }
Beispiel #10
0
 asyncApplication(bindingFn) {
     var zone = createNgZone();
     var completer = PromiseWrapper.completer();
     zone.run(() => {
         PromiseWrapper.then(bindingFn(zone), (bindings) => {
             completer.resolve(this._initApp(zone, bindings));
         });
     });
     return completer.promise;
 }
     .then((stylesAndNormalizedViewDirMetas) => {
     var childPromises = [];
     var normalizedViewDirMetas = stylesAndNormalizedViewDirMetas.slice(1);
     var parsedTemplate = this._templateParser.parse(compMeta.template.template, normalizedViewDirMetas, compMeta.type.name);
     var changeDetectorFactories = this._cdCompiler.compileComponentRuntime(compMeta.type, compMeta.changeDetection, parsedTemplate);
     changeDetectorFactory = changeDetectorFactories[0];
     styles = stylesAndNormalizedViewDirMetas[0];
     commands = this._compileCommandsRuntime(compMeta, templateId, parsedTemplate, changeDetectorFactories, compilingComponentCacheKeys, childPromises);
     return PromiseWrapper.all(childPromises);
 })
Beispiel #12
0
 RouterOutlet.prototype.reuse = function (nextInstruction) {
     var previousInstruction = this._currentInstruction;
     this._currentInstruction = nextInstruction;
     if (lang_1.isBlank(this._componentRef)) {
         throw new exceptions_1.BaseException("Cannot reuse an outlet that does not contain a component.");
     }
     return async_1.PromiseWrapper.resolve(route_lifecycle_reflector_1.hasLifecycleHook(hookMod.onReuse, this._currentInstruction.componentType) ?
         this._componentRef.instance.onReuse(nextInstruction, previousInstruction) :
         true);
 };
 RouteRegistry.prototype._recognizePrimaryRoute = function (parsedUrl, parentComponent) {
     var _this = this;
     var componentRecognizer = this._rules.get(parentComponent);
     if (lang_1.isBlank(componentRecognizer)) {
         return _resolveToNull;
     }
     // Matches some beginning part of the given URL
     var possibleMatches = componentRecognizer.recognize(parsedUrl);
     var matchPromises = collection_1.ListWrapper.map(possibleMatches, function (candidate) { return _this._completePrimaryRouteMatch(candidate); });
     return async_1.PromiseWrapper.all(matchPromises).then(mostSpecific);
 };
 PlatformRef_.prototype.asyncApplication = function (bindingFn) {
     var _this = this;
     var zone = createNgZone();
     var completer = async_1.PromiseWrapper.completer();
     zone.run(function () {
         async_1.PromiseWrapper.then(bindingFn(zone), function (bindings) {
             completer.resolve(_this._initApp(zone, bindings));
         });
     });
     return completer.promise;
 };
 Testability.prototype._runCallbacksIfReady = function () {
     var _this = this;
     if (!this.isStable()) {
         return; // Not ready
     }
     // Schedules the call backs in a new frame so that it is always async.
     async_1.PromiseWrapper.resolve(null).then(function (_) {
         while (_this._callbacks.length !== 0) {
             (_this._callbacks.pop())();
         }
     });
 };
Beispiel #16
0
 /**
  * Called by the {@link Router} when an outlet reuses a component across navigations.
  * This method in turn is responsible for calling the `onReuse` hook of its child.
  */
 deactivate(nextInstruction) {
     var next = _resolveToTrue;
     if (isPresent(this._componentRef) && isPresent(this._currentInstruction) &&
         hasLifecycleHook(hookMod.onDeactivate, this._currentInstruction.componentType)) {
         next = PromiseWrapper.resolve(this._componentRef.instance.onDeactivate(nextInstruction, this._currentInstruction));
     }
     return next.then((_) => {
         if (isPresent(this._componentRef)) {
             this._componentRef.dispose();
             this._componentRef = null;
         }
     });
 }
Beispiel #17
0
 // TODO(btford): it'd be nice to remove this method as part of cleaning up the traversal logic
 // Since refactoring `Router.generate` to return an instruction rather than a string, it's not
 // guaranteed that the `componentType`s for the terminal async routes have been loaded by the time
 // we begin navigation. The method below simply traverses instructions and resolves any components
 // for which `componentType` is not present
 /** @internal */
 _settleInstruction(instruction) {
     var unsettledInstructions = [];
     if (isBlank(instruction.component.componentType)) {
         unsettledInstructions.push(instruction.component.resolveComponentType().then((type) => { this.registry.configFromComponent(type); }));
     }
     if (isPresent(instruction.child)) {
         unsettledInstructions.push(this._settleInstruction(instruction.child));
     }
     StringMapWrapper.forEach(instruction.auxInstruction, (instruction, _) => {
         unsettledInstructions.push(this._settleInstruction(instruction));
     });
     return PromiseWrapper.all(unsettledInstructions);
 }
Beispiel #18
0
export function bootstrapWebWorkerCommon(appComponentType, bus, appProviders = null) {
    var bootstrapProcess = PromiseWrapper.completer();
    var appPromise = platform().asyncApplication((zone) => {
        // 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 subscription;
        var emitter = bus.from(SETUP_CHANNEL);
        subscription = ObservableWrapper.subscribe(emitter, (message) => {
            var bindings = [applicationCommonBindings(), webWorkerProviders(appComponentType, bus, message)];
            if (isPresent(appProviders)) {
                bindings.push(appProviders);
            }
            bootstrapProcess.resolve(bindings);
            ObservableWrapper.dispose(subscription);
        });
        ObservableWrapper.callNext(bus.to(SETUP_CHANNEL), "ready");
        return bootstrapProcess.promise;
    });
    return PromiseWrapper.then(appPromise, (app) => app.bootstrap(appComponentType));
}
Beispiel #19
0
 RouterOutlet.prototype.deactivate = function (nextInstruction) {
     var _this = this;
     var next = _resolveToTrue;
     if (lang_1.isPresent(this._componentRef) && lang_1.isPresent(this._currentInstruction) &&
         route_lifecycle_reflector_1.hasLifecycleHook(hookMod.onDeactivate, this._currentInstruction.componentType)) {
         next = async_1.PromiseWrapper.resolve(this._componentRef.instance.onDeactivate(nextInstruction, this._currentInstruction));
     }
     return next.then(function (_) {
         if (lang_1.isPresent(_this._componentRef)) {
             _this._componentRef.dispose();
             _this._componentRef = null;
         }
     });
 };
 compileInHost(componentType) {
     var metadatas = reflector.annotations(componentType);
     var compiledHostTemplate = null;
     for (var i = 0; i < metadatas.length; i++) {
         var metadata = metadatas[i];
         if (metadata instanceof CompiledHostTemplate) {
             compiledHostTemplate = metadata;
             break;
         }
     }
     if (isBlank(compiledHostTemplate)) {
         throw new BaseException(`No precompiled template for component ${stringify(componentType)} found`);
     }
     return PromiseWrapper.resolve(this._createProtoView(compiledHostTemplate));
 }
Beispiel #21
0
 /**
  * Called by the {@link Router} during recognition phase of a navigation.
  *
  * If the new child component has a different Type than the existing child component,
  * this will resolve to `false`. You can't reuse an old component when the new component
  * is of a different Type.
  *
  * Otherwise, this method delegates to the child component's `canReuse` hook if it exists,
  * or resolves to true if the hook is not present.
  */
 canReuse(nextInstruction) {
     var result;
     if (isBlank(this._currentInstruction) ||
         this._currentInstruction.componentType != nextInstruction.componentType) {
         result = false;
     }
     else if (hasLifecycleHook(hookMod.canReuse, this._currentInstruction.componentType)) {
         result = this._componentRef.instance.canReuse(nextInstruction, this._currentInstruction);
     }
     else {
         result = nextInstruction == this._currentInstruction ||
             (isPresent(nextInstruction.params) && isPresent(this._currentInstruction.params) &&
                 StringMapWrapper.equals(nextInstruction.params, this._currentInstruction.params));
     }
     return PromiseWrapper.resolve(result);
 }
Beispiel #22
0
 RouterOutlet.prototype.canReuse = function (nextInstruction) {
     var result;
     if (lang_1.isBlank(this._currentInstruction) ||
         this._currentInstruction.componentType != nextInstruction.componentType) {
         result = false;
     }
     else if (route_lifecycle_reflector_1.hasLifecycleHook(hookMod.canReuse, this._currentInstruction.componentType)) {
         result = this._componentRef.instance.canReuse(nextInstruction, this._currentInstruction);
     }
     else {
         result = nextInstruction == this._currentInstruction ||
             (lang_1.isPresent(nextInstruction.params) && lang_1.isPresent(this._currentInstruction.params) &&
                 collection_1.StringMapWrapper.equals(nextInstruction.params, this._currentInstruction.params));
     }
     return async_1.PromiseWrapper.resolve(result);
 };
Beispiel #23
0
 _loadStyles(plainStyles, absUrls, encapsulate) {
     var promises = absUrls.map((absUrl) => {
         var cacheKey = `${absUrl}${encapsulate ? '.shim' : ''}`;
         var result = this._styleCache.get(cacheKey);
         if (isBlank(result)) {
             result = this._xhr.get(absUrl).then((style) => {
                 var styleWithImports = extractStyleUrls(this._urlResolver, absUrl, style);
                 return this._loadStyles([styleWithImports.style], styleWithImports.styleUrls, encapsulate);
             });
             this._styleCache.set(cacheKey, result);
         }
         return result;
     });
     return PromiseWrapper.all(promises).then((nestedStyles) => {
         var result = plainStyles.map(plainStyle => this._shimIfNeeded(plainStyle, encapsulate));
         nestedStyles.forEach(styles => styles.forEach(style => result.push(style)));
         return result;
     });
 }
 zone.run(function () {
     async_1.PromiseWrapper.then(bindingFn(zone), function (bindings) {
         completer.resolve(_this._initApp(zone, bindings));
     });
 });
Beispiel #25
0
 zone.run(() => {
     PromiseWrapper.then(bindingFn(zone), (bindings) => {
         completer.resolve(this._initApp(zone, bindings));
     });
 });
Beispiel #26
0
import { PromiseWrapper, EventEmitter, ObservableWrapper } from 'angular2/src/core/facade/async';
import { Map, StringMapWrapper, ListWrapper } from 'angular2/src/core/facade/collection';
import { isBlank, isString, StringWrapper, isPresent } from 'angular2/src/core/facade/lang';
import { BaseException } from 'angular2/src/core/facade/exceptions';
import { stringifyInstruction, stringifyInstructionPath, stringifyInstructionQuery } from './instruction';
import { getCanActivateHook } from './route_lifecycle_reflector';
let _resolveToTrue = PromiseWrapper.resolve(true);
let _resolveToFalse = PromiseWrapper.resolve(false);
/**
 * The `Router` is responsible for mapping URLs to components.
 *
 * You can see the state of the router by inspecting the read-only field `router.navigating`.
 * This may be useful for showing a spinner, for instance.
 *
 * ## Concepts
 *
 * Routers and component instances have a 1:1 correspondence.
 *
 * The router holds reference to a number of {@link RouterOutlet}.
 * An outlet is a placeholder that the router dynamically fills in depending on the current URL.
 *
 * When the router navigates from a URL, it must first recognize it and serialize it into an
 * `Instruction`.
 * The router uses the `RouteRegistry` to get an `Instruction`.
 */
export class Router {
    constructor(registry, parent, hostComponent) {
        this.registry = registry;
        this.parent = parent;
        this.hostComponent = hostComponent;
        this.navigating = false;
Beispiel #27
0
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import { PromiseWrapper } from 'angular2/src/core/facade/async';
import { StringMapWrapper } from 'angular2/src/core/facade/collection';
import { isBlank, isPresent } from 'angular2/src/core/facade/lang';
import { BaseException } from 'angular2/src/core/facade/exceptions';
import { Directive, Attribute, DynamicComponentLoader, ElementRef, Injector, provide } from 'angular2/angular2';
import * as routerMod from './router';
import { RouteParams } from './instruction';
import { ROUTE_DATA } from './route_data';
import * as hookMod from './lifecycle_annotations';
import { hasLifecycleHook } from './route_lifecycle_reflector';
let _resolveToTrue = PromiseWrapper.resolve(true);
/**
 * A router outlet is a placeholder that Angular dynamically fills based on the application's route.
 *
 * ## Use
 *
 * ```
 * <router-outlet></router-outlet>
 * ```
 */
export let RouterOutlet = class {
    constructor(_elementRef, _loader, _parentRouter, nameAttr) {
        this._elementRef = _elementRef;
        this._loader = _loader;
        this._parentRouter = _parentRouter;
        this.name = null;
Beispiel #28
0
 _afterPromiseFinishNavigating(promise) {
     return PromiseWrapper.catchError(promise.then((_) => this._finishNavigating()), (err) => {
         this._finishNavigating();
         throw err;
     });
 }
Beispiel #29
0
 return next.then((_) => PromiseWrapper.all(promises));
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var route_recognizer_1 = require('./route_recognizer');
var instruction_1 = require('./instruction');
var collection_1 = require('angular2/src/core/facade/collection');
var async_1 = require('angular2/src/core/facade/async');
var lang_1 = require('angular2/src/core/facade/lang');
var exceptions_1 = require('angular2/src/core/facade/exceptions');
var route_config_impl_1 = require('./route_config_impl');
var reflection_1 = require('angular2/src/core/reflection/reflection');
var di_1 = require('angular2/src/core/di');
var route_config_nomalizer_1 = require('./route_config_nomalizer');
var url_parser_1 = require('./url_parser');
var _resolveToNull = async_1.PromiseWrapper.resolve(null);
/**
 * The RouteRegistry holds route configurations for each component in an Angular app.
 * It is responsible for creating Instructions from URLs, and generating URLs based on route and
 * parameters.
 */
var RouteRegistry = (function () {
    function RouteRegistry() {
        this._rules = new collection_1.Map();
    }
    /**
     * Given a component and a configuration object, add the route to this registry
     */
    RouteRegistry.prototype.config = function (parentComponent, config) {
        config = route_config_nomalizer_1.normalizeRouteConfig(config);
        // this is here because Dart type guard reasons