chore: fix DDC errors / warnings

Closes #7195
This commit is contained in:
Misko Hevery 2016-02-19 11:49:31 -08:00 committed by Miško Hevery
parent ef9e40e82b
commit 14f0e9ada8
88 changed files with 527 additions and 468 deletions

View File

@ -1,6 +1,7 @@
import {ControlValueAccessor} from './control_value_accessor';
import {AbstractControlDirective} from './abstract_control_directive';
import {unimplemented} from 'angular2/src/facade/exceptions';
import {AsyncValidatorFn, ValidatorFn} from './validators';
/**
* A base class that all control directive extend.
@ -12,8 +13,8 @@ export abstract class NgControl extends AbstractControlDirective {
name: string = null;
valueAccessor: ControlValueAccessor = null;
get validator(): Function { return unimplemented(); }
get asyncValidator(): Function { return unimplemented(); }
get validator(): ValidatorFn { return <ValidatorFn>unimplemented(); }
get asyncValidator(): AsyncValidatorFn { return <AsyncValidatorFn>unimplemented(); }
abstract viewToModelUpdate(newValue: any): void;
}

View File

@ -16,7 +16,8 @@ import {ControlContainer} from './control_container';
import {controlPath, composeValidators, composeAsyncValidators} from './shared';
import {ControlGroup} from '../model';
import {Form} from './form_interface';
import {Validators, NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {AsyncValidatorFn, ValidatorFn} from './validators';
const controlGroupProvider =
CONST_EXPR(new Provider(ControlContainer, {useExisting: forwardRef(() => NgControlGroup)}));
@ -106,7 +107,7 @@ export class NgControlGroup extends ControlContainer implements OnInit,
*/
get formDirective(): Form { return this._parent.formDirective; }
get validator(): Function { return composeValidators(this._validators); }
get validator(): ValidatorFn { return composeValidators(this._validators); }
get asyncValidator(): Function { return composeAsyncValidators(this._asyncValidators); }
get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); }
}

View File

@ -27,7 +27,8 @@ import {
selectValueAccessor
} from './shared';
import {Control} from '../model';
import {Validators, NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {ValidatorFn, AsyncValidatorFn} from './validators';
const controlNameBinding =
@ -136,9 +137,9 @@ export class NgControlName extends NgControl implements OnChanges,
get formDirective(): any { return this._parent.formDirective; }
get validator(): Function { return composeValidators(this._validators); }
get validator(): ValidatorFn { return composeValidators(this._validators); }
get asyncValidator(): Function { return composeAsyncValidators(this._asyncValidators); }
get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); }
get control(): Control { return this.formDirective.getControl(this); }
}

View File

@ -23,6 +23,7 @@ import {
isPropertyUpdated,
selectValueAccessor
} from './shared';
import {ValidatorFn, AsyncValidatorFn} from './validators';
const formControlBinding =
CONST_EXPR(new Provider(NgControl, {useExisting: forwardRef(() => NgFormControl)}));
@ -110,9 +111,9 @@ export class NgFormControl extends NgControl implements OnChanges {
get path(): string[] { return []; }
get validator(): Function { return composeValidators(this._validators); }
get validator(): ValidatorFn { return composeValidators(this._validators); }
get asyncValidator(): Function { return composeAsyncValidators(this._asyncValidators); }
get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); }
get control(): Control { return this.form; }

View File

@ -3,7 +3,6 @@ import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async';
import {
OnChanges,
SimpleChange,
Query,
Directive,
forwardRef,
Provider,
@ -14,7 +13,7 @@ import {
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
import {NgControl} from './ng_control';
import {Control} from '../model';
import {Validators, NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {
setUpControl,
isPropertyUpdated,
@ -22,6 +21,7 @@ import {
composeValidators,
composeAsyncValidators
} from './shared';
import {ValidatorFn, AsyncValidatorFn} from './validators';
const formControlBinding =
CONST_EXPR(new Provider(NgControl, {useExisting: forwardRef(() => NgModel)}));
@ -88,9 +88,9 @@ export class NgModel extends NgControl implements OnChanges {
get path(): string[] { return []; }
get validator(): Function { return composeValidators(this._validators); }
get validator(): ValidatorFn { return composeValidators(this._validators); }
get asyncValidator(): Function { return composeAsyncValidators(this._asyncValidators); }
get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); }
viewToModelUpdate(newValue: any): void {
this.viewModel = newValue;

View File

@ -10,3 +10,11 @@ Function normalizeValidator(dynamic validator){
}
}
Function normalizeAsyncValidator(dynamic validator){
if (validator is Validator) {
return (c) => validator.validate(c);
} else {
return validator;
}
}

View File

@ -1,14 +1,18 @@
import {Validator} from './validators';
import {Control} from "../model";
import {AbstractControl} from "../model";
import {Validator, ValidatorFn, AsyncValidatorFn} from './validators';
export type ctrlFunc = ((c: Control) => {
[key: string]: any
});
export function normalizeValidator(validator: (ctrlFunc | Validator)): ctrlFunc {
export function normalizeValidator(validator: ValidatorFn | Validator): ValidatorFn {
if ((<Validator>validator).validate !== undefined) {
return (c: Control) => (<Validator>validator).validate(c);
return (c: AbstractControl) => (<Validator>validator).validate(c);
} else {
return <ctrlFunc>validator;
return <ValidatorFn>validator;
}
}
export function normalizeAsyncValidator(validator: AsyncValidatorFn | Validator): AsyncValidatorFn {
if ((<Validator>validator).validate !== undefined) {
return (c: AbstractControl) => Promise.resolve((<Validator>validator).validate(c));
} else {
return <AsyncValidatorFn>validator;
}
}

View File

@ -14,7 +14,8 @@ import {NumberValueAccessor} from './number_value_accessor';
import {CheckboxControlValueAccessor} from './checkbox_value_accessor';
import {SelectControlValueAccessor} from './select_control_value_accessor';
import {RadioControlValueAccessor} from './radio_control_value_accessor';
import {normalizeValidator} from './normalize_validator';
import {normalizeValidator, normalizeAsyncValidator} from './normalize_validator';
import {ValidatorFn, AsyncValidatorFn} from './validators';
export function controlPath(name: string, parent: ControlContainer): string[] {
@ -56,13 +57,14 @@ function _throwError(dir: AbstractControlDirective, message: string): void {
throw new BaseException(`${message} '${path}'`);
}
export function composeValidators(validators: /* Array<Validator|Function> */ any[]): Function {
export function composeValidators(validators: /* Array<Validator|Function> */ any[]): ValidatorFn {
return isPresent(validators) ? Validators.compose(validators.map(normalizeValidator)) : null;
}
export function composeAsyncValidators(
validators: /* Array<Validator|Function> */ any[]): Function {
return isPresent(validators) ? Validators.composeAsync(validators.map(normalizeValidator)) : null;
validators: /* Array<Validator|Function> */ any[]): AsyncValidatorFn {
return isPresent(validators) ? Validators.composeAsync(validators.map(normalizeAsyncValidator)) :
null;
}
export function isPropertyUpdated(changes: {[key: string]: any}, viewModel: any): boolean {

View File

@ -1,11 +1,12 @@
import {forwardRef, Provider, OpaqueToken, Attribute, Directive} from 'angular2/core';
import {forwardRef, Provider, Attribute, Directive} from 'angular2/core';
import {CONST_EXPR} from 'angular2/src/facade/lang';
import {Validators, NG_VALIDATORS} from '../validators';
import {Control} from '../model';
import {AbstractControl} from '../model';
import * as modelModule from '../model';
import {NumberWrapper} from "angular2/src/facade/lang";
/**
* An interface that can be implemented by classes that can act as validators.
*
@ -23,7 +24,7 @@ import {NumberWrapper} from "angular2/src/facade/lang";
* }
* ```
*/
export interface Validator { validate(c: modelModule.Control): {[key: string]: any}; }
export interface Validator { validate(c: modelModule.AbstractControl): {[key: string]: any}; }
const REQUIRED_VALIDATOR =
CONST_EXPR(new Provider(NG_VALIDATORS, {useValue: Validators.required, multi: true}));
@ -45,6 +46,11 @@ const REQUIRED_VALIDATOR =
export class RequiredValidator {
}
export interface ValidatorFn { (c: AbstractControl): {[key: string]: any}; }
export interface AsyncValidatorFn {
(c: AbstractControl): any /*Promise<{[key: string]: any}>|Observable<{[key: string]: any}>*/;
}
/**
* Provivder which adds {@link MinLengthValidator} to {@link NG_VALIDATORS}.
*
@ -64,13 +70,13 @@ const MIN_LENGTH_VALIDATOR = CONST_EXPR(
providers: [MIN_LENGTH_VALIDATOR]
})
export class MinLengthValidator implements Validator {
private _validator: Function;
private _validator: ValidatorFn;
constructor(@Attribute("minlength") minLength: string) {
this._validator = Validators.minLength(NumberWrapper.parseInt(minLength, 10));
}
validate(c: Control): {[key: string]: any} { return this._validator(c); }
validate(c: AbstractControl): {[key: string]: any} { return this._validator(c); }
}
/**
@ -92,13 +98,13 @@ const MAX_LENGTH_VALIDATOR = CONST_EXPR(
providers: [MAX_LENGTH_VALIDATOR]
})
export class MaxLengthValidator implements Validator {
private _validator: Function;
private _validator: ValidatorFn;
constructor(@Attribute("maxlength") maxLength: string) {
this._validator = Validators.maxLength(NumberWrapper.parseInt(maxLength, 10));
}
validate(c: Control): {[key: string]: any} { return this._validator(c); }
validate(c: AbstractControl): {[key: string]: any} { return this._validator(c); }
}
@ -121,11 +127,11 @@ const PATTERN_VALIDATOR = CONST_EXPR(
providers: [PATTERN_VALIDATOR]
})
export class PatternValidator implements Validator {
private _validator: Function;
private _validator: ValidatorFn;
constructor(@Attribute("pattern") pattern: string) {
this._validator = Validators.pattern(pattern);
}
validate(c: Control): {[key: string]: any} { return this._validator(c); }
validate(c: AbstractControl): {[key: string]: any} { return this._validator(c); }
}

View File

@ -2,6 +2,7 @@ import {Injectable} from 'angular2/core';
import {StringMapWrapper} from 'angular2/src/facade/collection';
import {isPresent, isArray, CONST_EXPR, Type} from 'angular2/src/facade/lang';
import * as modelModule from './model';
import {ValidatorFn, AsyncValidatorFn} from './directives/validators';
/**
@ -56,16 +57,18 @@ export class FormBuilder {
group(controlsConfig: {[key: string]: any},
extra: {[key: string]: any} = null): modelModule.ControlGroup {
var controls = this._reduceControls(controlsConfig);
var optionals = isPresent(extra) ? StringMapWrapper.get(extra, "optionals") : null;
var validator = isPresent(extra) ? StringMapWrapper.get(extra, "validator") : null;
var asyncValidator = isPresent(extra) ? StringMapWrapper.get(extra, "asyncValidator") : null;
var optionals = <{[key: string]: boolean}>(
isPresent(extra) ? StringMapWrapper.get(extra, "optionals") : null);
var validator: ValidatorFn = isPresent(extra) ? StringMapWrapper.get(extra, "validator") : null;
var asyncValidator: AsyncValidatorFn =
isPresent(extra) ? StringMapWrapper.get(extra, "asyncValidator") : null;
return new modelModule.ControlGroup(controls, optionals, validator, asyncValidator);
}
/**
* Construct a new {@link Control} with the given `value`,`validator`, and `asyncValidator`.
*/
control(value: Object, validator: Function = null,
asyncValidator: Function = null): modelModule.Control {
control(value: Object, validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null): modelModule.Control {
return new modelModule.Control(value, validator, asyncValidator);
}
@ -73,8 +76,8 @@ export class FormBuilder {
* Construct an array of {@link Control}s from the given `controlsConfig` array of
* configuration, with the given optional `validator` and `asyncValidator`.
*/
array(controlsConfig: any[], validator: Function = null,
asyncValidator: Function = null): modelModule.ControlArray {
array(controlsConfig: any[], validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null): modelModule.ControlArray {
var controls = controlsConfig.map(c => this._createControl(c));
return new modelModule.ControlArray(controls, validator, asyncValidator);
}
@ -98,12 +101,12 @@ export class FormBuilder {
} else if (isArray(controlConfig)) {
var value = controlConfig[0];
var validator = controlConfig.length > 1 ? controlConfig[1] : null;
var asyncValidator = controlConfig.length > 2 ? controlConfig[2] : null;
var validator: ValidatorFn = controlConfig.length > 1 ? controlConfig[1] : null;
var asyncValidator: AsyncValidatorFn = controlConfig.length > 2 ? controlConfig[2] : null;
return this.control(value, validator, asyncValidator);
} else {
return this.control(controlConfig);
}
}
}
}

View File

@ -1,7 +1,8 @@
import {StringWrapper, isPresent, isBlank, normalizeBool} from 'angular2/src/facade/lang';
import {isPresent, isBlank, normalizeBool} from 'angular2/src/facade/lang';
import {Observable, EventEmitter, ObservableWrapper} from 'angular2/src/facade/async';
import {PromiseWrapper} from 'angular2/src/facade/promise';
import {StringMapWrapper, ListWrapper} from 'angular2/src/facade/collection';
import {ValidatorFn, AsyncValidatorFn} from './directives/validators';
/**
* Indicates that a Control is valid, i.e. that no errors exist in the input value.
@ -64,7 +65,7 @@ export abstract class AbstractControl {
private _parent: ControlGroup | ControlArray;
private _asyncValidationSubscription: any;
constructor(public validator: Function, public asyncValidator: Function) {}
constructor(public validator: ValidatorFn, public asyncValidator: AsyncValidatorFn) {}
get value(): any { return this._value; }
@ -137,15 +138,17 @@ export abstract class AbstractControl {
}
}
private _runValidator() { return isPresent(this.validator) ? this.validator(this) : null; }
private _runValidator(): {[key: string]: any} {
return isPresent(this.validator) ? this.validator(this) : null;
}
private _runAsyncValidator(emitEvent: boolean): void {
if (isPresent(this.asyncValidator)) {
this._status = PENDING;
this._cancelExistingSubscription();
var obs = toObservable(this.asyncValidator(this));
this._asyncValidationSubscription =
ObservableWrapper.subscribe(obs, res => this.setErrors(res, {emitEvent: emitEvent}));
this._asyncValidationSubscription = ObservableWrapper.subscribe(
obs, (res: {[key: string]: any}) => this.setErrors(res, {emitEvent: emitEvent}));
}
}
@ -268,7 +271,8 @@ export class Control extends AbstractControl {
/** @internal */
_onChange: Function;
constructor(value: any = null, validator: Function = null, asyncValidator: Function = null) {
constructor(value: any = null, validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null) {
super(validator, asyncValidator);
this._value = value;
this.updateValueAndValidity({onlySelf: true, emitEvent: false});
@ -331,8 +335,8 @@ export class ControlGroup extends AbstractControl {
private _optionals: {[key: string]: boolean};
constructor(public controls: {[key: string]: AbstractControl},
optionals: {[key: string]: boolean} = null, validator: Function = null,
asyncValidator: Function = null) {
optionals: {[key: string]: boolean} = null, validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null) {
super(validator, asyncValidator);
this._optionals = isPresent(optionals) ? optionals : {};
this._initObservables();
@ -444,8 +448,8 @@ export class ControlGroup extends AbstractControl {
* ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview))
*/
export class ControlArray extends AbstractControl {
constructor(public controls: AbstractControl[], validator: Function = null,
asyncValidator: Function = null) {
constructor(public controls: AbstractControl[], validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null) {
super(validator, asyncValidator);
this._initObservables();
this._setParentForControls();

View File

@ -5,6 +5,7 @@ import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {OpaqueToken} from 'angular2/core';
import * as modelModule from './model';
import {ValidatorFn, AsyncValidatorFn} from './directives/validators';
/**
* Providers for validators to be used for {@link Control}s in a form.
@ -43,7 +44,7 @@ export class Validators {
/**
* Validator that requires controls to have a non-empty value.
*/
static required(control: modelModule.Control): {[key: string]: boolean} {
static required(control: modelModule.AbstractControl): {[key: string]: boolean} {
return isBlank(control.value) || (isString(control.value) && control.value == "") ?
{"required": true} :
null;
@ -52,8 +53,8 @@ export class Validators {
/**
* Validator that requires controls to have a value of a minimum length.
*/
static minLength(minLength: number): Function {
return (control: modelModule.Control): {[key: string]: any} => {
static minLength(minLength: number): ValidatorFn {
return (control: modelModule.AbstractControl): {[key: string]: any} => {
if (isPresent(Validators.required(control))) return null;
var v: string = control.value;
return v.length < minLength ?
@ -65,8 +66,8 @@ export class Validators {
/**
* Validator that requires controls to have a value of a maximum length.
*/
static maxLength(maxLength: number): Function {
return (control: modelModule.Control): {[key: string]: any} => {
static maxLength(maxLength: number): ValidatorFn {
return (control: modelModule.AbstractControl): {[key: string]: any} => {
if (isPresent(Validators.required(control))) return null;
var v: string = control.value;
return v.length > maxLength ?
@ -78,8 +79,8 @@ export class Validators {
/**
* Validator that requires a control to match a regex to its value.
*/
static pattern(pattern: string): Function {
return (control: modelModule.Control): {[key: string]: any} => {
static pattern(pattern: string): ValidatorFn {
return (control: modelModule.AbstractControl): {[key: string]: any} => {
if (isPresent(Validators.required(control))) return null;
let regex = new RegExp(`^${pattern}$`);
let v: string = control.value;
@ -91,13 +92,13 @@ export class Validators {
/**
* No-op validator.
*/
static nullValidator(c: any): {[key: string]: boolean} { return null; }
static nullValidator(c: modelModule.AbstractControl): {[key: string]: boolean} { return null; }
/**
* Compose multiple validators into a single function that returns the union
* of the individual error maps.
*/
static compose(validators: Function[]): Function {
static compose(validators: ValidatorFn[]): ValidatorFn {
if (isBlank(validators)) return null;
var presentValidators = validators.filter(isPresent);
if (presentValidators.length == 0) return null;
@ -107,13 +108,13 @@ export class Validators {
};
}
static composeAsync(validators: Function[]): Function {
static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn {
if (isBlank(validators)) return null;
var presentValidators = validators.filter(isPresent);
if (presentValidators.length == 0) return null;
return function(control: modelModule.AbstractControl) {
let promises = _executeValidators(control, presentValidators).map(_convertToPromise);
let promises = _executeAsyncValidators(control, presentValidators).map(_convertToPromise);
return PromiseWrapper.all(promises).then(_mergeErrors);
};
}
@ -123,13 +124,20 @@ function _convertToPromise(obj: any): any {
return PromiseWrapper.isPromise(obj) ? obj : ObservableWrapper.toPromise(obj);
}
function _executeValidators(control: modelModule.AbstractControl, validators: Function[]): any[] {
function _executeValidators(control: modelModule.AbstractControl,
validators: ValidatorFn[]): any[] {
return validators.map(v => v(control));
}
function _executeAsyncValidators(control: modelModule.AbstractControl,
validators: AsyncValidatorFn[]): any[] {
return validators.map(v => v(control));
}
function _mergeErrors(arrayOfErrors: any[]): {[key: string]: any} {
var res = arrayOfErrors.reduce((res, errors) => {
return isPresent(errors) ? StringMapWrapper.merge(<any>res, <any>errors) : res;
}, {});
var res: {[key: string]: any} =
arrayOfErrors.reduce((res: {[key: string]: any}, errors: {[key: string]: any}) => {
return isPresent(errors) ? StringMapWrapper.merge(res, errors) : res;
}, {});
return StringMapWrapper.isEmpty(res) ? null : res;
}

View File

@ -22,7 +22,7 @@ class ObservableStrategy {
}
class PromiseStrategy {
createSubscription(async: any, updateLatestValue: any): any {
createSubscription(async: Promise<any>, updateLatestValue: (v: any) => any): any {
return async.then(updateLatestValue);
}

View File

@ -48,7 +48,7 @@ export class I18nPluralPipe implements PipeTransform {
transform(value: number, args: any[] = null): string {
var key: string;
var valueStr: string;
var pluralMap: {[count: string]: string} = args[0];
var pluralMap: {[count: string]: string} = <{[count: string]: string}>(args[0]);
if (!isStringMap(pluralMap)) {
throw new InvalidPipeArgumentException(I18nPluralPipe, pluralMap);

View File

@ -37,7 +37,7 @@ import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
@Injectable()
export class I18nSelectPipe implements PipeTransform {
transform(value: string, args: any[] = null): string {
var mapping: {[key: string]: string} = args[0];
var mapping: {[key: string]: string} = <{[count: string]: string}>(args[0]);
if (!isStringMap(mapping)) {
throw new InvalidPipeArgumentException(I18nSelectPipe, mapping);
}

View File

@ -146,8 +146,9 @@ class ProtoViewVisitor implements TemplateAstVisitor {
var directiveIndex = new DirectiveIndex(this.boundElementCount - 1, directiveIndexAsNumber);
var directiveMetadata = ast.directive;
var outputsArray = [];
StringMapWrapper.forEach(ast.directive.outputs, (eventName, dirProperty) => outputsArray.push(
[dirProperty, eventName]));
StringMapWrapper.forEach(
ast.directive.outputs,
(eventName: string, dirProperty: string) => outputsArray.push([dirProperty, eventName]));
var directiveRecord = new DirectiveRecord({
directiveIndex: directiveIndex,
callAfterContentInit:

View File

@ -31,7 +31,7 @@ export abstract class CompileMetadataWithIdentifier {
abstract toJson(): {[key: string]: any};
get identifier(): CompileIdentifierMetadata { return unimplemented(); }
get identifier(): CompileIdentifierMetadata { return <CompileIdentifierMetadata>unimplemented(); }
}
export abstract class CompileMetadataWithType extends CompileMetadataWithIdentifier {
@ -41,9 +41,9 @@ export abstract class CompileMetadataWithType extends CompileMetadataWithIdentif
abstract toJson(): {[key: string]: any};
get type(): CompileTypeMetadata { return unimplemented(); }
get type(): CompileTypeMetadata { return <CompileTypeMetadata>unimplemented(); }
get identifier(): CompileIdentifierMetadata { return unimplemented(); }
get identifier(): CompileIdentifierMetadata { return <CompileIdentifierMetadata>unimplemented(); }
}
export class CompileIdentifierMetadata implements CompileMetadataWithIdentifier {
@ -628,4 +628,4 @@ function objFromJson(obj: any, fn: (a: {[key: string]: any}) => any): any {
function objToJson(obj: any): string | {[key: string]: any} {
return (isString(obj) || isBlank(obj)) ? obj : obj.toJson();
}
}

View File

@ -234,7 +234,7 @@ class ProtoViewBuilderVisitor<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> implement
attrAsts: TemplateAst[]): string[][] {
var attrs = visitAndReturnContext(this, attrAsts, {});
directives.forEach(directiveMeta => {
StringMapWrapper.forEach(directiveMeta.hostAttributes, (value, name) => {
StringMapWrapper.forEach(directiveMeta.hostAttributes, (value: string, name: string) => {
var prevValue = attrs[name];
attrs[name] = isPresent(prevValue) ? mergeAttributeValue(name, prevValue, value) : value;
});
@ -330,12 +330,14 @@ class ProtoViewBuilderVisitor<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> implement
}
function mapToKeyValueArray(data: {[key: string]: string}): string[][] {
var entryArray = [];
StringMapWrapper.forEach(data, (value, name) => { entryArray.push([name, value]); });
var entryArray: string[][] = [];
StringMapWrapper.forEach(data,
(value: string, name: string) => { entryArray.push([name, value]); });
// We need to sort to get a defined output order
// for tests and for caching generated artifacts...
ListWrapper.sort(entryArray, (entry1, entry2) => StringWrapper.compare(entry1[0], entry2[0]));
var keyValueArray = [];
ListWrapper.sort<string[]>(entryArray, (entry1: string[], entry2: string[]) =>
StringWrapper.compare(entry1[0], entry2[0]));
var keyValueArray: string[][] = [];
entryArray.forEach((entry) => { keyValueArray.push([entry[0], entry[1]]); });
return keyValueArray;
}

View File

@ -53,9 +53,9 @@ export class StyleCompiler {
private _loadStyles(plainStyles: string[], absUrls: string[],
encapsulate: boolean): Promise<Array<string | any[]>> {
var promises = absUrls.map((absUrl) => {
var promises: Promise<string[]>[] = absUrls.map((absUrl: string): Promise<string[]> => {
var cacheKey = `${absUrl}${encapsulate ? '.shim' : ''}`;
var result = this._styleCache.get(cacheKey);
var result: Promise<string[]> = this._styleCache.get(cacheKey);
if (isBlank(result)) {
result = this._xhr.get(absUrl).then((style) => {
var styleWithImports = extractStyleUrls(this._urlResolver, absUrl, style);
@ -66,7 +66,7 @@ export class StyleCompiler {
}
return result;
});
return PromiseWrapper.all(promises).then((nestedStyles: string[][]) => {
return PromiseWrapper.all<string[]>(promises).then((nestedStyles: string[][]) => {
var result: Array<string | any[]> =
plainStyles.map(plainStyle => this._shimIfNeeded(plainStyle, encapsulate));
nestedStyles.forEach(styles => result.push(styles));

View File

@ -505,7 +505,7 @@ class TemplateParseVisitor implements HtmlAstVisitor {
sourceSpan: ParseSourceSpan,
targetPropertyAsts: BoundElementPropertyAst[]) {
if (isPresent(hostProps)) {
StringMapWrapper.forEach(hostProps, (expression, propName) => {
StringMapWrapper.forEach(hostProps, (expression: string, propName: string) => {
var exprAst = this._parseBinding(expression, sourceSpan);
targetPropertyAsts.push(
this._createElementPropertyAst(elementName, propName, exprAst, sourceSpan));
@ -517,7 +517,7 @@ class TemplateParseVisitor implements HtmlAstVisitor {
sourceSpan: ParseSourceSpan,
targetEventAsts: BoundEventAst[]) {
if (isPresent(hostListeners)) {
StringMapWrapper.forEach(hostListeners, (expression, propName) => {
StringMapWrapper.forEach(hostListeners, (expression: string, propName: string) => {
this._parseEvent(propName, expression, sourceSpan, [], targetEventAsts);
});
}
@ -645,7 +645,7 @@ class TemplateParseVisitor implements HtmlAstVisitor {
var allDirectiveEvents = new Set<string>();
directives.forEach(directive => {
StringMapWrapper.forEach(directive.directive.outputs,
(eventName, _) => { allDirectiveEvents.add(eventName); });
(eventName: string, _) => { allDirectiveEvents.add(eventName); });
});
events.forEach(event => {
if (isPresent(event.target) || !SetWrapper.has(allDirectiveEvents, event.name)) {

View File

@ -128,7 +128,7 @@ function _createPlatform(providers?: Array<Type | Provider | any[]>): PlatformRe
}
function _runPlatformInitializers(injector: Injector): void {
let inits: Function[] = injector.getOptional(PLATFORM_INITIALIZER);
let inits: Function[] = <Function[]>injector.getOptional(PLATFORM_INITIALIZER);
if (isPresent(inits)) inits.forEach(init => init());
}
@ -150,7 +150,7 @@ export abstract class PlatformRef {
* Retrieve the platform {@link Injector}, which is the parent injector for
* every Angular application on the page and provides singleton providers.
*/
get injector(): Injector { return unimplemented(); };
get injector(): Injector { throw unimplemented(); };
/**
* Instantiate a new Angular application on the page.
@ -222,7 +222,7 @@ export class PlatformRef_ extends PlatformRef {
asyncApplication(bindingFn: (zone: NgZone) => Promise<Array<Type | Provider | any[]>>,
additionalProviders?: Array<Type | Provider | any[]>): Promise<ApplicationRef> {
var zone = createNgZone();
var completer = PromiseWrapper.completer();
var completer = PromiseWrapper.completer<ApplicationRef>();
if (bindingFn === null) {
completer.resolve(this._initApp(zone, additionalProviders));
} else {
@ -342,12 +342,12 @@ export abstract class ApplicationRef {
/**
* Retrieve the application {@link Injector}.
*/
get injector(): Injector { return unimplemented(); };
get injector(): Injector { return <Injector>unimplemented(); };
/**
* Retrieve the application {@link NgZone}.
*/
get zone(): NgZone { return unimplemented(); };
get zone(): NgZone { return <NgZone>unimplemented(); };
/**
* Dispose of this application and all of its components.
@ -369,7 +369,7 @@ export abstract class ApplicationRef {
/**
* Get a list of component types registered to this application.
*/
get componentTypes(): Type[] { return unimplemented(); };
get componentTypes(): Type[] { return <Type[]>unimplemented(); };
}
export class ApplicationRef_ extends ApplicationRef {
@ -449,13 +449,13 @@ export class ApplicationRef_ extends ApplicationRef {
completer.reject(e, e.stack);
}
});
return completer.promise.then(_ => {
return completer.promise.then<ComponentRef>((ref: ComponentRef) => {
let c = this._injector.get(Console);
if (assertionsEnabled()) {
c.log(
"Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.");
}
return _;
return ref;
});
}

View File

@ -64,8 +64,9 @@ export class DynamicProtoChangeDetector implements ProtoChangeDetector {
export function createPropertyRecords(definition: ChangeDetectorDefinition): ProtoRecord[] {
var recordBuilder = new ProtoRecordBuilder();
ListWrapper.forEachWithIndex(definition.bindingRecords,
(b, index) => recordBuilder.add(b, definition.variableNames, index));
ListWrapper.forEachWithIndex(
definition.bindingRecords,
(b: BindingRecord, index: number) => recordBuilder.add(b, definition.variableNames, index));
return coalesce(recordBuilder.records);
}

View File

@ -91,19 +91,19 @@ export class DebugElement extends DebugNode {
}
queryAll(predicate: Predicate<DebugElement>): DebugElement[] {
var matches = [];
var matches: DebugElement[] = [];
_queryElementChildren(this, predicate, matches);
return matches;
}
queryAllNodes(predicate: Predicate<DebugNode>): DebugNode[] {
var matches = [];
var matches: DebugNode[] = [];
_queryNodeChildren(this, predicate, matches);
return matches;
}
get children(): DebugElement[] {
var children = [];
var children: DebugElement[] = [];
this.childNodes.forEach((node) => {
if (node instanceof DebugElement) {
children.push(node);

View File

@ -73,7 +73,7 @@ export class DebugDomRenderer implements Renderer {
if (isPresent(debugNode)) {
var debugParent = debugNode.parent;
if (viewRootNodes.length > 0 && isPresent(debugParent)) {
var debugViewRootNodes = [];
var debugViewRootNodes: DebugNode[] = [];
viewRootNodes.forEach((rootNode) => debugViewRootNodes.push(getDebugNode(rootNode)));
debugParent.insertChildrenAfter(debugNode, debugViewRootNodes);
}

View File

@ -513,7 +513,7 @@ export class ProviderBuilder {
*/
export function resolveFactory(provider: Provider): ResolvedFactory {
var factoryFn: Function;
var resolvedDeps;
var resolvedDeps: Dependency[];
if (isPresent(provider.useClass)) {
var useClass = resolveForwardRef(provider.useClass);
factoryFn = reflector.factory(useClass);
@ -619,7 +619,7 @@ function _constructDependencies(factoryFunction: Function, dependencies: any[]):
}
function _dependenciesFor(typeOrFunc): Dependency[] {
var params = reflector.parameters(typeOrFunc);
var params: any[][] = reflector.parameters(typeOrFunc);
if (isBlank(params)) return [];
if (params.some(isBlank)) {
throw new NoAnnotationError(typeOrFunc, params);

View File

@ -115,8 +115,9 @@ export class AppView implements ChangeDispatcher {
this.disposables = disposables;
this.appElements = appElements;
var localsMap = new Map<string, any>();
StringMapWrapper.forEach(this.proto.templateVariableBindings,
(templateName, _) => { localsMap.set(templateName, null); });
StringMapWrapper.forEach(
this.proto.templateVariableBindings,
(templateName: string, _: string) => { localsMap.set(templateName, null); });
for (var i = 0; i < appElements.length; i++) {
var appEl = appElements[i];
var providerTokens = [];
@ -125,13 +126,14 @@ export class AppView implements ChangeDispatcher {
providerTokens.push(appEl.proto.protoInjector.getProviderAtIndex(j).key.token);
}
}
StringMapWrapper.forEach(appEl.proto.directiveVariableBindings, (directiveIndex, name) => {
if (isBlank(directiveIndex)) {
localsMap.set(name, appEl.nativeElement);
} else {
localsMap.set(name, appEl.getDirectiveAtIndex(directiveIndex));
}
});
StringMapWrapper.forEach(appEl.proto.directiveVariableBindings,
(directiveIndex: number, name: string) => {
if (isBlank(directiveIndex)) {
localsMap.set(name, appEl.nativeElement);
} else {
localsMap.set(name, appEl.getDirectiveAtIndex(directiveIndex));
}
});
this.renderer.setElementDebugInfo(
appEl.nativeElement, new RenderDebugInfo(appEl.getInjector(), appEl.getComponent(),
providerTokens, localsMap));

View File

@ -41,7 +41,7 @@ export abstract class ViewContainerRef {
* Anchor element that specifies the location of this container in the containing View.
* <!-- TODO: rename to anchorElement -->
*/
get element(): ElementRef { return unimplemented(); }
get element(): ElementRef { return <ElementRef>unimplemented(); }
/**
* Destroys all Views in this container.
@ -60,7 +60,7 @@ export abstract class ViewContainerRef {
/**
* Returns the number of Views currently attached to this container.
*/
get length(): number { return unimplemented(); };
get length(): number { return <number>unimplemented(); };
/**
* Instantiates an Embedded View based on the {@link TemplateRef `templateRef`} and inserts it

View File

@ -6,9 +6,9 @@ export abstract class ViewRef {
/**
* @internal
*/
get changeDetectorRef(): ChangeDetectorRef { return unimplemented(); };
get changeDetectorRef(): ChangeDetectorRef { return <ChangeDetectorRef>unimplemented(); };
get destroyed(): boolean { return unimplemented(); }
get destroyed(): boolean { return <boolean>unimplemented(); }
}
/**
@ -21,7 +21,7 @@ export abstract class ViewRef {
* {@link AppViewManager#createHostViewInContainer}, {@link ViewContainerRef#createHostView}.
*/
export abstract class HostViewRef extends ViewRef {
get rootNodes(): any[] { return unimplemented(); };
get rootNodes(): any[] { return <any[]>unimplemented(); };
}
/**
@ -88,7 +88,7 @@ export abstract class EmbeddedViewRef extends ViewRef {
*/
abstract hasLocal(variableName: string): boolean;
get rootNodes(): any[] { return unimplemented(); };
get rootNodes(): any[] { return <any[]>unimplemented(); };
}
export class ViewRef_ implements EmbeddedViewRef, HostViewRef {
@ -116,4 +116,4 @@ export class HostViewFactoryRef_ implements HostViewFactoryRef {
constructor(private _hostViewFactory: HostViewFactory) {}
get internalHostViewFactory(): HostViewFactory { return this._hostViewFactory; }
}
}

View File

@ -87,7 +87,7 @@ export class Reflector {
}
}
parameters(typeOrFunc: /*Type*/ any): any[] {
parameters(typeOrFunc: /*Type*/ any): any[][] {
if (this._injectableInfo.has(typeOrFunc)) {
var res = this._getReflectionInfo(typeOrFunc).parameters;
return isPresent(res) ? res : [];
@ -148,7 +148,7 @@ export class Reflector {
}
/** @internal */
_getReflectionInfo(typeOrFunc: any) {
_getReflectionInfo(typeOrFunc: any): ReflectionInfo {
if (isPresent(this._usedKeys)) {
this._usedKeys.add(typeOrFunc);
}

View File

@ -25,7 +25,7 @@ class TimerWrapper {
}
class ObservableWrapper {
static StreamSubscription subscribe(Stream s, Function onNext,
static StreamSubscription subscribe/*<T>*/(Stream s, onNext(/*=T*/ value),
[onError, onComplete]) {
return s.listen(onNext,
onError: onError, onDone: onComplete, cancelOnError: true);

View File

@ -1,10 +1,8 @@
import {global, isPresent, noop} from 'angular2/src/facade/lang';
import {global, noop} from 'angular2/src/facade/lang';
export {PromiseWrapper, PromiseCompleter} from 'angular2/src/facade/promise';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import {Subscription} from 'rxjs/Subscription';
import {Operator} from 'rxjs/Operator';
import {PromiseObservable} from 'rxjs/observable/PromiseObservable';
import {toPromise} from 'rxjs/operator/toPromise';

View File

@ -33,15 +33,15 @@ class IterableMap extends IterableBase<List> {
}
class MapWrapper {
static Map clone(Map m) => new Map.from(m);
static Map/*<K,V>*/ clone/*<K,V>*/(Map/*<K,V>*/ m) => new Map.from(m);
// in opposite to JS, Dart does not create a new map
static Map createFromStringMap(Map m) => m;
static Map/*<K,V>*/ createFromStringMap/*<K,V>*/(Map/*<K,V>*/ m) => m;
// in opposite to JS, Dart does not create a new map
static Map toStringMap(Map m) => m;
static Map/*<K,V>*/ toStringMap/*<K,V>*/(Map/*<K,V>*/ m) => m;
static Map createFromPairs(List pairs) => pairs.fold({}, (m, p) {
static Map/*<K,V>*/ createFromPairs/*<K,V>*/(List pairs) => pairs.fold(/*<K,V>*/{}, (m, p) {
m[p[0]] = p[1];
return m;
});
@ -52,29 +52,29 @@ class MapWrapper {
}
}
static Iterable iterable(Map m) => new IterableMap(m);
static List keys(Map m) => m.keys.toList();
static List values(Map m) => m.values.toList();
static Iterable/*<List<dynamic>>*/ iterable/*<K,V>*/(Map/*<K,V>*/ m) => new IterableMap(m);
static List/*<K>*/ keys/*<K,V>*/(Map/*<K,V>*/ m) => m.keys.toList();
static List/*<V>*/ values/*<K,V>*/(Map/*<K,V>*/ m) => m.values.toList();
}
class StringMapWrapper {
static Map create() => {};
static bool contains(Map map, key) => map.containsKey(key);
static get(Map map, key) => map[key];
static void set(Map map, key, value) {
static Map/*<String,V>*/ create/*<V>*/() => {};
static bool contains/*<V>*/(Map/*<String,V>*/ map, String key) => map.containsKey(key);
static get/*<V>*/(Map/*<String,V>*/ map, String key) => map[key];
static void set/*<V>*/(Map/*<String,V>*/ map, String key, /*=V*/value) {
map[key] = value;
}
static void delete(Map m, k) {
static void delete/*<V>*/(Map/*<String,V>*/ m, String k) {
m.remove(k);
}
static void forEach(Map m, fn(v, k)) {
static void forEach/*<V>*/(Map/*<String,V>*/ m, fn(/*=V*/ v, String k)) {
m.forEach((k, v) => fn(v, k));
}
static Map merge(Map a, Map b) {
var m = new Map.from(a);
static Map/*<String,V>*/ merge/*<V>*/(Map/*<String,V>*/ a, Map/*<String,V>*/ b) {
var m = new Map/*<String,V>*/.from(a);
if (b != null) {
b.forEach((k, v) => m[k] = v);
}
@ -86,7 +86,7 @@ class StringMapWrapper {
}
static bool isEmpty(Map m) => m.isEmpty;
static bool equals(Map m1, Map m2) {
static bool equals/*<V>*/(Map/*<String,V>*/ m1, Map/*<String,V>*/ m2) {
if (m1.length != m2.length) {
return false;
}
@ -102,9 +102,9 @@ class StringMapWrapper {
typedef bool Predicate<T>(T item);
class ListWrapper {
static List clone(Iterable l) => new List.from(l);
static List createFixedSize(int size) => new List(size);
static List createGrowableSize(int size) =>
static List/*<T>*/ clone/*<T>*/(Iterable/*<T>*/ l) => new List.from(l);
static List/*<T>*/ createFixedSize/*<T>*/(int size) => new List(size);
static List/*<T>*/ createGrowableSize/*<T>*/(int size) =>
new List.generate(size, (_) => null, growable: true);
static UnmodifiableListView createImmutable(List input) {
return new UnmodifiableListView(input);
@ -116,43 +116,43 @@ class ListWrapper {
static int lastIndexOf(List list, value, [int startIndex = null]) =>
list.lastIndexOf(value, startIndex == null ? list.length : startIndex);
static void forEachWithIndex(List list, fn(item, index)) {
static void forEachWithIndex/*<T>*/(List/*<T>*/ list, fn(/*=T*/ item, int index)) {
for (var i = 0; i < list.length; ++i) {
fn(list[i], i);
}
}
static first(List list) => list.isEmpty ? null : list.first;
static last(List list) => list.isEmpty ? null : list.last;
static List reversed(List list) => list.reversed.toList();
static List concat(List a, List b) {
static /*=T*/ first/*<T>*/(List/*<T>*/ list) => list.isEmpty ? null : list.first;
static /*=T*/ last/*<T>*/(List/*<T>*/ list) => list.isEmpty ? null : list.last;
static List/*<T>*/ reversed/*<T>*/(List/*<T>*/ list) => list.reversed.toList();
static List/*<T>*/ concat/*<T>*/(List/*<T>*/ a, List/*<T>*/ b) {
return new List()
..length = a.length + b.length
..setRange(0, a.length, a)
..setRange(a.length, a.length + b.length, b);
}
static void insert(List l, int index, value) {
static void insert/*<T>*/(List/*<T>*/ l, int index, /*=T*/ value) {
l.insert(index, value);
}
static removeAt(List l, int index) => l.removeAt(index);
static void removeAll(List list, List items) {
static void removeAll/*<T>*/(List/*<T>*/ list, List/*<T>*/ items) {
for (var i = 0; i < items.length; ++i) {
list.remove(items[i]);
}
}
static bool remove(List list, item) => list.remove(item);
static bool remove/*<T>*/(List/*<T>*/ list, /*=T*/ item) => list.remove(item);
static void clear(List l) {
l.clear();
}
static bool isEmpty(Iterable list) => list.isEmpty;
static void fill(List l, value, [int start = 0, int end]) {
static void fill/*<T>*/(List/*<T>*/ l, /*=T*/ value, [int start = 0, int end]) {
l.fillRange(_startOffset(l, start), _endOffset(l, end), value);
}
static bool equals(List a, List b) {
static bool equals/*<T>*/(List/*<T>*/ a, List/*<T>*/ b) {
if (a.length != b.length) return false;
for (var i = 0; i < a.length; ++i) {
if (a[i] != b[i]) return false;
@ -160,7 +160,7 @@ class ListWrapper {
return true;
}
static List slice(List l, [int from = 0, int to]) {
static List/*<T>*/ slice/*<T>*/(List/*<T>*/ l, [int from = 0, int to]) {
from = _startOffset(l, from);
to = _endOffset(l, to);
//in JS if from > to an empty array is returned
@ -170,7 +170,7 @@ class ListWrapper {
return l.sublist(from, to);
}
static List splice(List l, int from, int length) {
static List/*<T>*/ splice/*<T>*/(List/*<T>*/ l, int from, int length) {
from = _startOffset(l, from);
var to = from + length;
var sub = l.sublist(from, to);
@ -178,7 +178,7 @@ class ListWrapper {
return sub;
}
static void sort(List l, [compareFn(a, b) = null]) {
static void sort/*<T>*/(List/*<T>*/ l, [int compareFn(/*=T*/a, /*=T*/b) = null]) {
if (compareFn == null) {
l.sort();
} else {
@ -232,7 +232,11 @@ class ListWrapper {
bool isListLikeIterable(obj) => obj is Iterable;
bool areIterablesEqual(Iterable a, Iterable b, Function comparator) {
bool areIterablesEqual/*<T>*/(
Iterable/*<T>*/ a,
Iterable/*<T>*/ b,
bool comparator(/*=T*/a, /*=T*/b))
{
var iterator1 = a.iterator;
var iterator2 = b.iterator;
@ -241,11 +245,11 @@ bool areIterablesEqual(Iterable a, Iterable b, Function comparator) {
var done2 = !iterator2.moveNext();
if (done1 && done2) return true;
if (done1 || done2) return false;
if (!comparator(iterator2.current, iterator2.current)) return false;
if (!comparator(iterator1.current, iterator2.current)) return false;
}
}
void iterateListLike(iter, fn(item)) {
void iterateListLike/*<T>*/(Iterable/*<T>*/ iter, fn(/*=T*/item)) {
assert(iter is Iterable);
for (var item in iter) {
fn(item);
@ -253,9 +257,9 @@ void iterateListLike(iter, fn(item)) {
}
class SetWrapper {
static Set createFromList(List l) => new Set.from(l);
static bool has(Set s, key) => s.contains(key);
static void delete(Set m, k) {
static Set/*<T>*/ createFromList/*<T>*/(List/*<T>*/ l) => new Set.from(l);
static bool has/*<T>*/(Set/*<T>*/ s, /*=T*/key) => s.contains(key);
static void delete/*<T>*/(Set/*<T>*/ m, /*=T*/k) {
m.remove(k);
}
}

View File

@ -20,16 +20,16 @@ class CONST {
const IS_DART = true;
bool isPresent(obj) => obj != null;
bool isBlank(obj) => obj == null;
bool isString(obj) => obj is String;
bool isFunction(obj) => obj is Function;
bool isType(obj) => obj is Type;
bool isStringMap(obj) => obj is Map;
bool isArray(obj) => obj is List;
bool isPromise(obj) => obj is Future;
bool isNumber(obj) => obj is num;
bool isDate(obj) => obj is DateTime;
bool isPresent(Object obj) => obj != null;
bool isBlank(Object obj) => obj == null;
bool isString(Object obj) => obj is String;
bool isFunction(Object obj) => obj is Function;
bool isType(Object obj) => obj is Type;
bool isStringMap(Object obj) => obj is Map;
bool isArray(Object obj) => obj is List;
bool isPromise(Object obj) => obj is Future;
bool isNumber(Object obj) => obj is num;
bool isDate(Object obj) => obj is DateTime;
String stringify(obj) {
final exp = new RegExp(r"from Function '(\w+)'");

View File

@ -4,22 +4,21 @@ import 'dart:async';
import 'dart:async' as async;
class PromiseWrapper {
static Future resolve(obj) => new Future.value(obj);
static Future/*<T>*/ resolve/*<T>*/(dynamic /*=T*/ obj) => new Future.value(obj);
static Future reject(obj, stackTrace) => new Future.error(obj,
stackTrace != null ? stackTrace : obj is Error ? obj.stackTrace : null);
static Future/*<T>*/ reject/*<T>*/(dynamic /*=T*/ obj, Object stackTrace) => new Future.error(obj,
stackTrace != null ? stackTrace : obj is Error ? (obj as Error).stackTrace : null);
static Future<List> all(List<dynamic> promises) {
static Future<List/*<T>*/> all/*<T>*/(List<dynamic> promises) {
return Future
.wait(promises.map((p) => p is Future ? p : new Future.value(p)));
.wait(promises.map((p) => p is Future ? p as Future/*<T>*/ : new Future/*<T>*/.value(p)));
}
static Future then(Future promise, success(value), [Function onError]) {
static Future/*<R>*/ then/*<T, R>*/(Future/*<T>*/ promise, dynamic /*=R*/ success(dynamic /*=T*/ value), [Function onError]) {
if (success == null) return promise.catchError(onError);
return promise.then(success, onError: onError);
}
static Future wrap(Function fn) {
static Future/*<T>*/ wrap/*<T>*/(dynamic /*=T*/ fn()) {
return new Future(fn);
}
@ -37,16 +36,14 @@ class PromiseWrapper {
return obj is Future;
}
static PromiseCompleter<dynamic> completer() =>
new PromiseCompleter(new Completer());
static PromiseCompleter/*<T>*/ completer/*<T>*/() =>
new PromiseCompleter();
}
class PromiseCompleter<T> {
final Completer<T> c;
final Completer<T> c = new Completer();
PromiseCompleter(this.c);
Future get promise => c.future;
Future<T> get promise => c.future;
void resolve(v) {
c.complete(v);

View File

@ -1,8 +1,15 @@
export interface PromiseCompleter<R> {
export class PromiseCompleter<R> {
promise: Promise<R>;
resolve: (value?: R | PromiseLike<R>) => void;
reject: (error?: any, stackTrace?: string) => void;
constructor() {
this.promise = new Promise((res, rej) => {
this.resolve = res;
this.reject = rej;
});
}
}
export class PromiseWrapper {
@ -17,7 +24,7 @@ export class PromiseWrapper {
return promise.catch(onError);
}
static all(promises: any[]): Promise<any> {
static all<T>(promises: (T | Promise<T>)[]): Promise<T[]> {
if (promises.length == 0) return Promise.resolve([]);
return Promise.all(promises);
}
@ -43,15 +50,5 @@ export class PromiseWrapper {
static isPromise(obj: any): boolean { return obj instanceof Promise; }
static completer(): PromiseCompleter<any> {
var resolve;
var reject;
var p = new Promise(function(res, rej) {
resolve = res;
reject = rej;
});
return {promise: p, resolve: resolve, reject: reject};
}
static completer<T>(): PromiseCompleter<T> { return new PromiseCompleter<T>(); }
}

View File

@ -31,7 +31,7 @@ export abstract class GenericBrowserDomAdapter extends DomAdapter {
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
};
StringMapWrapper.forEach(transEndEventNames, (value, key) => {
StringMapWrapper.forEach(transEndEventNames, (value: string, key: string) => {
if (isPresent(this.getStyle(element, key))) {
this._transitionEnd = value;
}

View File

@ -102,7 +102,7 @@ export class RouterOutlet implements OnDestroy {
var next = _resolveToTrue;
if (isPresent(this._componentRef) && isPresent(this._currentInstruction) &&
hasLifecycleHook(hookMod.routerOnDeactivate, this._currentInstruction.componentType)) {
next = PromiseWrapper.resolve(
next = <Promise<boolean>>PromiseWrapper.resolve(
(<OnDeactivate>this._componentRef.instance)
.routerOnDeactivate(nextInstruction, this._currentInstruction));
}
@ -127,7 +127,7 @@ export class RouterOutlet implements OnDestroy {
return _resolveToTrue;
}
if (hasLifecycleHook(hookMod.routerCanDeactivate, this._currentInstruction.componentType)) {
return PromiseWrapper.resolve(
return <Promise<boolean>>PromiseWrapper.resolve(
(<CanDeactivate>this._componentRef.instance)
.routerCanDeactivate(nextInstruction, this._currentInstruction));
}
@ -158,7 +158,7 @@ export class RouterOutlet implements OnDestroy {
(isPresent(nextInstruction.params) && isPresent(this._currentInstruction.params) &&
StringMapWrapper.equals(nextInstruction.params, this._currentInstruction.params));
}
return PromiseWrapper.resolve(result);
return <Promise<boolean>>PromiseWrapper.resolve(result);
}
ngOnDestroy(): void { this._parentRouter.unregisterPrimaryOutlet(this); }

View File

@ -195,7 +195,7 @@ export abstract class Instruction {
/** @internal */
_stringifyAux(): string {
var routes = [];
StringMapWrapper.forEach(this.auxInstruction, (auxInstruction, _) => {
StringMapWrapper.forEach(this.auxInstruction, (auxInstruction: Instruction, _: string) => {
routes.push(auxInstruction._stringifyPathMatrixAux());
});
if (routes.length > 0) {
@ -308,7 +308,7 @@ export class ComponentInstruction {
*/
constructor(public urlPath: string, public urlParams: string[], data: RouteData,
public componentType, public terminal: boolean, public specificity: string,
public params: {[key: string]: any} = null) {
public params: {[key: string]: string} = null) {
this.routeData = isPresent(data) ? data : BLANK_ROUTE_DATA;
}
}

View File

@ -5,7 +5,7 @@ import {global} from 'angular2/src/facade/lang';
// TODO(rado): find a better way to fix this, or remove if likely culprit
// https://github.com/systemjs/systemjs/issues/487 gets closed.
var __ignore_me = global;
var __make_dart_analyzer_happy: Promise<any> = null;
/**
* Defines route lifecycle method `routerOnActivate`, which is called by the router at the end of a
@ -27,7 +27,8 @@ var __ignore_me = global;
*/
export interface OnActivate {
routerOnActivate(nextInstruction: ComponentInstruction,
prevInstruction: ComponentInstruction): any;
prevInstruction: ComponentInstruction): any |
Promise<any>;
}
/**
@ -46,7 +47,8 @@ export interface OnActivate {
* {@example router/ts/reuse/reuse_example.ts region='reuseCmp'}
*/
export interface OnReuse {
routerOnReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
routerOnReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any |
Promise<any>;
}
/**
@ -66,7 +68,8 @@ export interface OnReuse {
*/
export interface OnDeactivate {
routerOnDeactivate(nextInstruction: ComponentInstruction,
prevInstruction: ComponentInstruction): any;
prevInstruction: ComponentInstruction): any |
Promise<any>;
}
/**
@ -90,7 +93,9 @@ export interface OnDeactivate {
* {@example router/ts/reuse/reuse_example.ts region='reuseCmp'}
*/
export interface CanReuse {
routerCanReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
routerCanReuse(nextInstruction: ComponentInstruction,
prevInstruction: ComponentInstruction): boolean |
Promise<boolean>;
}
/**
@ -114,5 +119,6 @@ export interface CanReuse {
*/
export interface CanDeactivate {
routerCanDeactivate(nextInstruction: ComponentInstruction,
prevInstruction: ComponentInstruction): any;
prevInstruction: ComponentInstruction): boolean |
Promise<boolean>;
}

View File

@ -27,9 +27,9 @@ export abstract class PlatformLocation {
abstract onPopState(fn: UrlChangeListener): void;
abstract onHashChange(fn: UrlChangeListener): void;
pathname: string;
search: string;
hash: string;
/* abstract */ get pathname(): string { return null; }
/* abstract */ get search(): string { return null; }
/* abstract */ get hash(): string { return null; }
abstract replaceState(state: any, title: string, url: string): void;

View File

@ -4,6 +4,8 @@ import {RegexSerializer} from '../rules/route_paths/regex_route_path';
export {RouteDefinition} from '../route_definition';
var __make_dart_analyzer_happy: Promise<any> = null;
/**
* The `RouteConfig` decorator defines routes for a given component.
*
@ -136,7 +138,7 @@ export class AuxRoute extends AbstractRoute {
*/
@CONST()
export class AsyncRoute extends AbstractRoute {
loader: Function;
loader: () => Promise<Type>;
aux: string = null;
constructor({name, useAsDefault, path, regex, serializer, data, loader}: RouteDefinition) {

View File

@ -92,7 +92,8 @@ export function normalizeRouteConfig(config: RouteDefinition,
}
function wrapLoaderToReconfigureRegistry(loader: Function, registry: RouteRegistry): Function {
function wrapLoaderToReconfigureRegistry(loader: Function, registry: RouteRegistry): () =>
Promise<Type> {
return () => {
return loader().then((componentType) => {
registry.configFromComponent(componentType);

View File

@ -18,7 +18,7 @@ export interface RouteDefinition {
regex?: string;
serializer?: RegexSerializer;
component?: Type | ComponentDefinition;
loader?: Function;
loader?: () => Promise<Type>;
redirectTo?: any[];
as?: string;
name?: string;
@ -34,6 +34,6 @@ export interface RouteDefinition {
*/
export interface ComponentDefinition {
type: string;
loader?: Function;
loader?: () => Promise<Type>;
component?: Type;
}

View File

@ -37,8 +37,9 @@ import {
import {normalizeRouteConfig, assertComponentExists} from './route_config/route_config_normalizer';
import {parser, Url, convertUrlParamsToArray, pathSegmentsToUrl} from './url_parser';
import {GeneratedUrl} from './rules/route_paths/route_path';
var _resolveToNull = PromiseWrapper.resolve(null);
var _resolveToNull = PromiseWrapper.resolve<Instruction>(null);
// A LinkItemArray is an array, which describes a set of routes
// The items in the array are found in groups:
@ -180,7 +181,7 @@ export class RouteRegistry {
(candidate: Promise<RouteMatch>) => candidate.then((candidate: RouteMatch) => {
if (candidate instanceof PathMatch) {
var auxParentInstructions =
var auxParentInstructions: Instruction[] =
ancestorInstructions.length > 0 ? [ListWrapper.last(ancestorInstructions)] : [];
var auxInstructions =
this._auxRoutesToUnresolved(candidate.remainingAux, auxParentInstructions);
@ -191,7 +192,7 @@ export class RouteRegistry {
return instruction;
}
var newAncestorInstructions = ancestorInstructions.concat([instruction]);
var newAncestorInstructions: Instruction[] = ancestorInstructions.concat([instruction]);
return this._recognize(candidate.remaining, newAncestorInstructions)
.then((childInstruction) => {
@ -220,7 +221,7 @@ export class RouteRegistry {
return PromiseWrapper.resolve(this.generateDefault(parentComponent));
}
return PromiseWrapper.all(matchPromises).then(mostSpecific);
return PromiseWrapper.all<Instruction>(matchPromises).then(mostSpecific);
}
private _auxRoutesToUnresolved(auxRoutes: Url[],
@ -400,7 +401,7 @@ export class RouteRegistry {
// we'll figure out the rest of the route when we resolve the instruction and
// perform a navigation
if (isBlank(routeRecognizer.handler.componentType)) {
var generatedUrl = routeRecognizer.generateComponentPathValues(routeParams);
var generatedUrl: GeneratedUrl = routeRecognizer.generateComponentPathValues(routeParams);
return new UnresolvedInstruction(() => {
return routeRecognizer.handler.resolveComponentType().then((_) => {
return this._generate(linkParams, ancestorInstructions, prevInstruction, _aux,
@ -416,7 +417,7 @@ export class RouteRegistry {
// Next, recognize auxiliary instructions.
// If we have an ancestor instruction, we preserve whatever aux routes are active from it.
while (linkParamIndex < linkParams.length && isArray(linkParams[linkParamIndex])) {
let auxParentInstruction = [parentInstruction];
let auxParentInstruction: Instruction[] = [parentInstruction];
let auxInstruction = this._generate(linkParams[linkParamIndex], auxParentInstruction, null,
true, _originalLink);
@ -436,7 +437,7 @@ export class RouteRegistry {
// TODO: throw that there are extra link params beyond the terminal component
}
} else {
let childAncestorComponents = ancestorInstructions.concat([instruction]);
let childAncestorComponents: Instruction[] = ancestorInstructions.concat([instruction]);
let remainingLinkParams = linkParams.slice(linkParamIndex);
childInstruction = this._generate(remainingLinkParams, childAncestorComponents, null, false,
_originalLink);

View File

@ -75,7 +75,7 @@ export class Router {
*
* You probably don't need to use this unless you're writing a reusable component.
*/
registerPrimaryOutlet(outlet: RouterOutlet): Promise<boolean> {
registerPrimaryOutlet(outlet: RouterOutlet): Promise<any> {
if (isPresent(outlet.name)) {
throw new BaseException(`registerPrimaryOutlet expects to be called with an unnamed outlet.`);
}
@ -109,7 +109,7 @@ export class Router {
*
* You probably don't need to use this unless you're writing a reusable component.
*/
registerAuxOutlet(outlet: RouterOutlet): Promise<boolean> {
registerAuxOutlet(outlet: RouterOutlet): Promise<any> {
var outletName = outlet.name;
if (isBlank(outletName)) {
throw new BaseException(`registerAuxOutlet expects to be called with an outlet with a name.`);
@ -230,7 +230,7 @@ export class Router {
unsettledInstructions.push(this._settleInstruction(instruction.child));
}
StringMapWrapper.forEach(instruction.auxInstruction, (instruction, _) => {
StringMapWrapper.forEach(instruction.auxInstruction, (instruction: Instruction, _) => {
unsettledInstructions.push(this._settleInstruction(instruction));
});
return PromiseWrapper.all(unsettledInstructions);
@ -311,7 +311,7 @@ export class Router {
next = this._outlet.routerCanDeactivate(componentInstruction);
}
// TODO: aux route lifecycle hooks
return next.then((result) => {
return next.then<boolean>((result): boolean | Promise<boolean> => {
if (result == false) {
return false;
}
@ -346,7 +346,7 @@ export class Router {
}
}
var promises = [];
var promises: Promise<any>[] = [];
this._auxRouters.forEach((router, name) => {
if (isPresent(instruction.auxInstruction[name])) {
promises.push(router.commit(instruction.auxInstruction[name]));
@ -405,7 +405,7 @@ export class Router {
}
private _getAncestorInstructions(): Instruction[] {
var ancestorInstructions = [this.currentInstruction];
var ancestorInstructions: Instruction[] = [this.currentInstruction];
var ancestorRouter: Router = this;
while (isPresent(ancestorRouter = ancestorRouter.parent)) {
ancestorInstructions.unshift(ancestorRouter.currentInstruction);
@ -534,7 +534,7 @@ function canActivateOne(nextInstruction: Instruction,
next = canActivateOne(nextInstruction.child,
isPresent(prevInstruction) ? prevInstruction.child : null);
}
return next.then((result) => {
return next.then<boolean>((result: boolean): boolean => {
if (result == false) {
return false;
}

View File

@ -6,15 +6,15 @@ import {RouteData, BLANK_ROUTE_DATA} from '../../instruction';
export class AsyncRouteHandler implements RouteHandler {
/** @internal */
_resolvedComponent: Promise<any> = null;
_resolvedComponent: Promise<Type> = null;
componentType: Type;
public data: RouteData;
constructor(private _loader: Function, data: {[key: string]: any} = null) {
constructor(private _loader: () => Promise<Type>, data: {[key: string]: any} = null) {
this.data = isPresent(data) ? new RouteData(data) : BLANK_ROUTE_DATA;
}
resolveComponentType(): Promise<any> {
resolveComponentType(): Promise<Type> {
if (isPresent(this._resolvedComponent)) {
return this._resolvedComponent;
}

View File

@ -113,7 +113,7 @@ export class UrlParser {
var path = matchUrlSegment(this._remaining);
this.capture(path);
var aux = [];
var aux: Url[] = [];
if (this.peekStartsWith('(')) {
aux = this.parseAuxiliaryRoutes();
}
@ -126,7 +126,7 @@ export class UrlParser {
this.capture('/');
child = this.parseSegment();
}
var queryParams = null;
var queryParams: {[key: string]: any} = null;
if (this.peekStartsWith('?')) {
queryParams = this.parseQueryParams();
}
@ -144,15 +144,15 @@ export class UrlParser {
var path = matchUrlSegment(this._remaining);
this.capture(path);
var matrixParams = null;
var matrixParams: {[key: string]: any} = null;
if (this.peekStartsWith(';')) {
matrixParams = this.parseMatrixParams();
}
var aux = [];
var aux: Url[] = [];
if (this.peekStartsWith('(')) {
aux = this.parseAuxiliaryRoutes();
}
var child = null;
var child: Url = null;
if (this.peekStartsWith('/') && !this.peekStartsWith('//')) {
this.capture('/');
child = this.parseSegment();
@ -161,7 +161,7 @@ export class UrlParser {
}
parseQueryParams(): {[key: string]: any} {
var params = {};
var params: {[key: string]: any} = {};
this.capture('?');
this.parseParam(params);
while (this._remaining.length > 0 && this.peekStartsWith('&')) {
@ -172,7 +172,7 @@ export class UrlParser {
}
parseMatrixParams(): {[key: string]: any} {
var params = {};
var params: {[key: string]: any} = {};
while (this._remaining.length > 0 && this.peekStartsWith(';')) {
this.capture(';');
this.parseParam(params);
@ -200,7 +200,7 @@ export class UrlParser {
}
parseAuxiliaryRoutes(): Url[] {
var routes = [];
var routes: Url[] = [];
this.capture('(');
while (!this.peekStartsWith(')') && this._remaining.length > 0) {
@ -215,4 +215,4 @@ export class UrlParser {
}
}
export var parser = new UrlParser();
export var parser = new UrlParser();

View File

@ -18,6 +18,6 @@ export function verifyNoBrowserErrors() {
}
return logEntry.level.value > webdriver.logging.Level.WARNING.value;
});
expect(filteredLog.length).toEqual(0);
expect(filteredLog).toEqual([]);
});
}

View File

@ -254,8 +254,9 @@ export class TestComponentBuilder {
DOM.appendChild(doc.body, rootEl);
return this._injector.get(DynamicComponentLoader)
.loadAsRoot(rootComponentType, `#${rootElId}`, this._injector)
.then((componentRef) => { return new ComponentFixture_(componentRef); });
var promise: Promise<ComponentRef> =
this._injector.get(DynamicComponentLoader)
.loadAsRoot(rootComponentType, `#${rootElId}`, this._injector);
return promise.then((componentRef) => { return new ComponentFixture_(componentRef); });
}
}

View File

@ -140,7 +140,7 @@ export function main() {
]);
var value = null;
c(new Control("invalid")).then(v => value = v);
(<Promise<any>>c(new Control("invalid"))).then(v => value = v);
tick(1);
@ -151,7 +151,7 @@ export function main() {
var c = Validators.composeAsync([asyncValidator("expected", {"one": true})]);
var value = null;
c(new Control("expected")).then(v => value = v);
(<Promise<any>>c(new Control("expected"))).then(v => value = v);
tick(1);
@ -162,7 +162,7 @@ export function main() {
var c = Validators.composeAsync([asyncValidator("expected", {"one": true}), null]);
var value = null;
c(new Control("invalid")).then(v => value = v);
(<Promise<any>>c(new Control("invalid"))).then(v => value = v);
tick(1);

View File

@ -23,6 +23,7 @@ import {
TimerWrapper
} from 'angular2/src/facade/async';
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
import {PromiseCompleter} from 'angular2/src/facade/promise';
export function main() {
describe("AsyncPipe", () => {
@ -116,16 +117,16 @@ export function main() {
describe("Promise", () => {
var message = new Object();
var pipe;
var completer;
var ref;
var pipe: AsyncPipe;
var completer: PromiseCompleter<any>;
var ref: SpyChangeDetectorRef;
// adds longer timers for passing tests in IE
var timer = (!isBlank(DOM) && browserDetection.isIE) ? 50 : 0;
beforeEach(() => {
completer = PromiseWrapper.completer();
ref = new SpyChangeDetectorRef();
pipe = new AsyncPipe(ref);
pipe = new AsyncPipe(<any>ref);
});
describe("transform", () => {

View File

@ -76,14 +76,15 @@ export function main() {
describe('compile templates', () => {
function runTests(compile) {
function runTests(compile: (components: Type[]) => Promise<any[]>) {
it('should throw for non components', inject([AsyncTestCompleter], (async) => {
PromiseWrapper.catchError(PromiseWrapper.wrap(() => compile([NonComponent])), (error) => {
expect(error.message)
.toEqual(
`Could not compile '${stringify(NonComponent)}' because it is not a component.`);
async.done();
});
PromiseWrapper.catchError(
PromiseWrapper.wrap(() => compile([NonComponent])), (error): any => {
expect(error.message)
.toEqual(
`Could not compile '${stringify(NonComponent)}' because it is not a component.`);
async.done();
});
}));
it('should compile host components', inject([AsyncTestCompleter], (async) => {

View File

@ -99,14 +99,14 @@ export function main() {
});
it('should contain a default value of "/packages" when nothing is provided for DART',
inject([UrlResolver], (resolver) => {
inject([UrlResolver], (resolver: UrlResolver) => {
if (IS_DART) {
expect(resolver.resolve(null, 'package:file')).toEqual('/packages/file');
}
}));
it('should contain a default value of "/" when nothing is provided for TS/ESM',
inject([UrlResolver], (resolver) => {
inject([UrlResolver], (resolver: UrlResolver) => {
if (!IS_DART) {
expect(resolver.resolve(null, 'package:file')).toEqual('/file');
}

View File

@ -65,8 +65,8 @@ export function main() {
});
}));
function mockAsyncAppInitializer(completer, providers: Array<any> = null,
injector?: Injector) {
function mockAsyncAppInitializer(completer: PromiseCompleter<any>,
providers: Array<any> = null, injector?: Injector) {
return () => {
if (providers != null) {
expectProviders(injector, providers);
@ -76,23 +76,11 @@ export function main() {
};
}
function createSpyPromiseCompleter(): SpyObject {
let completer = PromiseWrapper.completer();
let completerSpy = <any>new SpyObject();
// Note that in TypeScript we need to provide a value for the promise attribute
// whereas in dart we need to override the promise getter
completerSpy.promise = completer.promise;
completerSpy.spy("get:promise").andReturn(completer.promise);
completerSpy.spy("resolve").andCallFake(completer.resolve);
completerSpy.spy("reject").andCallFake(completer.reject);
return completerSpy;
}
it("should wait for asyncronous app initializers",
inject([AsyncTestCompleter, Injector], (async, injector) => {
let ref = new PlatformRef_(injector, null);
let completer = createSpyPromiseCompleter();
let completer: PromiseCompleter<any> = PromiseWrapper.completer();
let SYNC_PROVIDERS = [
new Provider(Bar, {useValue: new Bar()}),
new Provider(APP_INITIALIZER,
@ -102,8 +90,7 @@ export function main() {
.then((appRef) => {
expectProviders(appRef.injector,
SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1));
expect(completer.spy("resolve")).toHaveBeenCalled();
async.done();
completer.promise.then((_) => async.done());
});
}));
@ -111,13 +98,13 @@ export function main() {
inject([AsyncTestCompleter, Injector], (async, injector) => {
let ref = new PlatformRef_(injector, null);
let ASYNC_PROVIDERS = [new Provider(Foo, {useValue: new Foo()})];
let completer = createSpyPromiseCompleter();
let completer: PromiseCompleter<any> = PromiseWrapper.completer();
let SYNC_PROVIDERS = [
new Provider(Bar, {useValue: new Bar()}),
new Provider(APP_INITIALIZER,
{
useFactory: (injector) => mockAsyncAppInitializer(
completer, ASYNC_PROVIDERS, injector),
<any>completer, ASYNC_PROVIDERS, injector),
multi: true,
deps: [Injector]
})
@ -126,8 +113,7 @@ export function main() {
.then((appRef) => {
expectProviders(appRef.injector,
SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1));
expect(completer.spy("resolve")).toHaveBeenCalled();
async.done();
completer.promise.then((_) => async.done());
});
}));
});

View File

@ -18,6 +18,7 @@ import {Compiler} from 'angular2/src/core/linker/compiler';
import {reflector, ReflectionInfo} from 'angular2/src/core/reflection/reflection';
import {Compiler_} from "angular2/src/core/linker/compiler";
import {HostViewFactory} from 'angular2/src/core/linker/view';
import {HostViewFactoryRef_} from 'angular2/src/core/linker/view_ref';
export function main() {
describe('Compiler', () => {
@ -31,11 +32,12 @@ export function main() {
}));
it('should read the template from an annotation',
inject([AsyncTestCompleter, Compiler], (async, compiler) => {
inject([AsyncTestCompleter, Compiler], (async, compiler: Compiler) => {
compiler.compileInHost(SomeComponent)
.then((hostViewFactoryRef) => {
.then((hostViewFactoryRef: HostViewFactoryRef_) => {
expect(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory);
async.done();
return null;
});
}));

View File

@ -113,7 +113,7 @@ class SomeDirectiveWithoutMetadata {}
export function main() {
describe("DirectiveResolver", () => {
var resolver;
var resolver: DirectiveResolver;
beforeEach(() => { resolver = new DirectiveResolver(); });

View File

@ -34,7 +34,7 @@ export function main() {
describe("loading into a location", () => {
it('should work',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => {
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(
MyComp,
new ViewMetadata(
@ -52,7 +52,7 @@ export function main() {
it('should return a disposable component ref',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => {
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(
MyComp,
new ViewMetadata(
@ -72,7 +72,7 @@ export function main() {
it('should allow to dispose even if the location has been removed',
inject(
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => {
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp, new ViewMetadata({
template: '<child-cmp *ngIf="ctxBoolProp"></child-cmp>',
directives: [NgIf, ChildComp]
@ -109,7 +109,7 @@ export function main() {
it('should update host properties',
inject(
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => {
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(
MyComp, new ViewMetadata(
{template: '<location #loc></location>', directives: [Location]}))
@ -131,7 +131,7 @@ export function main() {
it('should leave the view tree in a consistent state if hydration fails',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => {
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp, new ViewMetadata({
template: '<div><location #loc></location></div>',
directives: [Location]
@ -147,13 +147,14 @@ export function main() {
expect(error.message).toContain("ThrownInConstructor");
expect(() => tc.detectChanges()).not.toThrow();
async.done();
return null;
});
});
}));
it('should throw if the variable does not exist',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => {
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(
MyComp,
new ViewMetadata(
@ -169,7 +170,7 @@ export function main() {
it('should allow to pass projectable nodes',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => {
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp,
new ViewMetadata({template: '<div #loc></div>', directives: []}))
.createAsync(MyComp)
@ -187,7 +188,7 @@ export function main() {
it('should throw if not enough projectable nodes are passed in',
inject(
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => {
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp,
new ViewMetadata({template: '<div #loc></div>', directives: []}))
.createAsync(MyComp)
@ -199,6 +200,7 @@ export function main() {
expect(e.message).toContain(
`The component ${stringify(DynamicallyLoadedWithNgContent)} has 1 <ng-content> elements, but only 0 slots were provided`);
async.done();
return null;
});
});
}));
@ -208,7 +210,7 @@ export function main() {
describe("loading next to a location", () => {
it('should work',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => {
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp, new ViewMetadata({
template: '<div><location #loc></location></div>',
directives: [Location]
@ -228,7 +230,7 @@ export function main() {
it('should return a disposable component ref',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => {
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp, new ViewMetadata({
template: '<div><location #loc></location></div>',
directives: [Location]
@ -262,7 +264,7 @@ export function main() {
it('should update host properties',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => {
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp, new ViewMetadata({
template: '<div><location #loc></location></div>',
directives: [Location]
@ -288,7 +290,7 @@ export function main() {
it('should allow to pass projectable nodes',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => {
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp, new ViewMetadata({template: '', directives: [Location]}))
.createAsync(MyComp)
.then((tc) => {
@ -309,7 +311,8 @@ export function main() {
describe('loadAsRoot', () => {
it('should allow to create, update and destroy components',
inject([AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector],
(async, loader, doc, injector) => {
(async: AsyncTestCompleter, loader: DynamicComponentLoader, doc,
injector: Injector) => {
var rootEl = createRootElement(doc, 'child-cmp');
DOM.appendChild(doc.body, rootEl);
loader.loadAsRoot(ChildComp, null, injector)
@ -338,7 +341,8 @@ export function main() {
it('should allow to pass projectable nodes',
inject([AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector],
(async, loader, doc, injector) => {
(async: AsyncTestCompleter, loader: DynamicComponentLoader, doc,
injector: Injector) => {
var rootEl = createRootElement(doc, 'dummy');
DOM.appendChild(doc.body, rootEl);
loader.loadAsRoot(DynamicallyLoadedWithNgContent, null, injector, null,

View File

@ -818,7 +818,8 @@ function declareTests() {
tcb.createAsync(MyComp).then(root => { fixture = root; });
tick();
var cmp = fixture.debugElement.children[0].getLocal('cmp');
var cmp: PushCmpWithAsyncPipe =
fixture.debugElement.children[0].getLocal('cmp');
fixture.detectChanges();
expect(cmp.numberOfChecks).toEqual(1);
@ -1155,7 +1156,7 @@ function declareTests() {
.createAsync(MyComp)
.then((fixture) => {
var tc = fixture.debugElement.children[0].children[0];
var dynamicVp = tc.inject(DynamicViewport);
var dynamicVp: DynamicViewport = tc.inject(DynamicViewport);
dynamicVp.done.then((_) => {
fixture.detectChanges();
expect(fixture.debugElement.children[0].children[1].nativeElement)
@ -1549,7 +1550,7 @@ function declareTests() {
it('should support moving embedded views around',
inject([TestComponentBuilder, AsyncTestCompleter, ANCHOR_ELEMENT],
(tcb, async, anchorElement) => {
(tcb: TestComponentBuilder, async, anchorElement) => {
tcb.overrideView(MyComp, new ViewMetadata({
template: '<div><div *someImpvp="ctxBoolProp">hello</div></div>',
directives: [SomeImperativeViewport]
@ -1950,7 +1951,7 @@ class SimpleImperativeViewComponent {
@Directive({selector: 'dynamic-vp'})
@Injectable()
class DynamicViewport {
done;
done: Promise<any>;
constructor(vc: ViewContainerRef, compiler: Compiler) {
var myService = new MyService();
myService.greeting = 'dynamic greet';

View File

@ -286,7 +286,7 @@ export function main() {
// important as we are removing the ng-content element during compilation,
// which could skrew up text node indices.
it('should support text nodes after content tags',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb, async) => {
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
tcb.overrideView(
MainComp,
@ -307,7 +307,7 @@ export function main() {
// important as we are moving style tags around during compilation,
// which could skrew up text node indices.
it('should support text nodes after style tags',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb, async) => {
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
tcb.overrideView(
MainComp,

View File

@ -43,7 +43,7 @@ class SimpleClass {}
export function main() {
describe("ViewResolver", () => {
var resolver;
var resolver: ViewResolver;
beforeEach(() => { resolver = new ViewResolver(); });

View File

@ -566,7 +566,7 @@ function commonTests() {
it('should call onTurnStart and onTurnDone for promises created outside of run body',
inject([AsyncTestCompleter], (async) => {
var promise;
var promise: Promise<any>;
macroTask(() => {
_zone.runOutsideAngular(() => {

View File

@ -674,7 +674,7 @@ function commonTests() {
logOnTurnStart();
logOnTurnDone();
var promise;
var promise: Promise<any>;
macroTask(() => {
_zone.runOutsideAngular(() => {

View File

@ -18,7 +18,7 @@ import {isBlank} from 'angular2/src/facade/lang';
export function main() {
describe('MockViewResolver', () => {
var viewResolver;
var viewResolver: MockViewResolver;
beforeEach(() => { viewResolver = new MockViewResolver(); });

View File

@ -25,7 +25,7 @@ import {provide, Inject, Injector, PLATFORM_INITIALIZER, APP_INITIALIZER} from '
import {disposePlatform} from 'angular2/src/core/application_ref';
import {ExceptionHandler} from 'angular2/src/facade/exceptions';
import {Testability, TestabilityRegistry} from 'angular2/src/core/testability/testability';
import {ComponentRef_} from "angular2/src/core/linker/dynamic_component_loader";
import {ComponentRef_, ComponentRef} from "angular2/src/core/linker/dynamic_component_loader";
@Component({selector: 'hello-app'})
@View({template: '{{greeting}} world!'})
@ -243,11 +243,11 @@ export function main() {
it('should register each application with the testability registry',
inject([AsyncTestCompleter], (async) => {
var refPromise1 = bootstrap(HelloRootCmp, testProviders);
var refPromise2 = bootstrap(HelloRootCmp2, testProviders);
var refPromise1: Promise<ComponentRef> = bootstrap(HelloRootCmp, testProviders);
var refPromise2: Promise<ComponentRef> = bootstrap(HelloRootCmp2, testProviders);
PromiseWrapper.all([refPromise1, refPromise2])
.then((refs: ApplicationRef[]) => {
.then((refs: ComponentRef[]) => {
var registry = refs[0].injector.get(TestabilityRegistry);
var testabilities =
[refs[0].injector.get(Testability), refs[1].injector.get(Testability)];

View File

@ -430,8 +430,8 @@ function syncRoutesWithSyncChildrenWithDefaultRoutesWithoutParams() {
}
function syncRoutesWithDynamicComponents() {
var fixture;
var tcb;
var fixture: ComponentFixture;
var tcb: TestComponentBuilder;
var rtr: Router;
beforeEachProviders(() => TEST_ROUTER_PROVIDERS);

View File

@ -56,17 +56,18 @@ export function main() {
var tcb: TestComponentBuilder;
var fixture: ComponentFixture;
var rtr;
var rtr: Router;
beforeEachProviders(() => TEST_ROUTER_PROVIDERS);
beforeEach(inject([TestComponentBuilder, Router], (tcBuilder, router) => {
tcb = tcBuilder;
rtr = router;
cmpInstanceCount = 0;
log = [];
eventBus = new EventEmitter();
}));
beforeEach(inject([TestComponentBuilder, Router],
(tcBuilder: TestComponentBuilder, router: Router) => {
tcb = tcBuilder;
rtr = router;
cmpInstanceCount = 0;
log = [];
eventBus = new EventEmitter();
}));
it('should call the routerOnActivate hook', inject([AsyncTestCompleter], (async) => {
compile(tcb)

View File

@ -49,7 +49,8 @@ export function main() {
describe('routerLink directive', function() {
var tcb: TestComponentBuilder;
var fixture: ComponentFixture;
var router, location;
var router: Router;
var location: Location;
beforeEachProviders(() => [
RouteRegistry,
@ -60,11 +61,12 @@ export function main() {
provide(TEMPLATE_TRANSFORMS, {useClass: RouterLinkTransform, multi: true})
]);
beforeEach(inject([TestComponentBuilder, Router, Location], (tcBuilder, rtr, loc) => {
tcb = tcBuilder;
router = rtr;
location = loc;
}));
beforeEach(inject([TestComponentBuilder, Router, Location],
(tcBuilder, rtr: Router, loc: Location) => {
tcb = tcBuilder;
router = rtr;
location = loc;
}));
function compile(template: string = "<router-outlet></router-outlet>") {
return tcb.overrideView(MyComp, new View({
@ -77,7 +79,7 @@ export function main() {
it('should generate absolute hrefs that include the base href',
inject([AsyncTestCompleter], (async) => {
location.setBaseHref('/my/base');
(<SpyLocation>location).setBaseHref('/my/base');
compile('<a href="hello" [routerLink]="[\'./User\']"></a>')
.then((_) => router.config(
[new Route({path: '/user', component: UserCmp, name: 'User'})]))
@ -345,7 +347,7 @@ export function main() {
// router navigation is async.
router.subscribe((_) => {
expect(location.urlChanges).toEqual(['/user']);
expect((<SpyLocation>location).urlChanges).toEqual(['/user']);
async.done();
});
});
@ -353,7 +355,7 @@ export function main() {
it('should navigate to link hrefs in presence of base href',
inject([AsyncTestCompleter], (async) => {
location.setBaseHref('/base');
(<SpyLocation>location).setBaseHref('/base');
compile('<a href="hello" [routerLink]="[\'./User\']"></a>')
.then((_) => router.config(
[new Route({path: '/user', component: UserCmp, name: 'User'})]))
@ -367,7 +369,7 @@ export function main() {
// router navigation is async.
router.subscribe((_) => {
expect(location.urlChanges).toEqual(['/base/user']);
expect((<SpyLocation>location).urlChanges).toEqual(['/base/user']);
async.done();
});
});

View File

@ -25,7 +25,7 @@ import {
export function main() {
describe('RouteRegistry', () => {
var registry;
var registry: RouteRegistry;
beforeEach(() => { registry = new RouteRegistry(RootHostCmp); });

View File

@ -30,10 +30,12 @@ import {
import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver';
import {provide} from 'angular2/core';
import {RouterOutlet} from 'angular2/src/router/directives/router_outlet';
export function main() {
describe('Router', () => {
var router, location;
var router: Router;
var location: Location;
beforeEachProviders(() => [
RouteRegistry,
@ -44,7 +46,7 @@ export function main() {
]);
beforeEach(inject([Router, Location], (rtr, loc) => {
beforeEach(inject([Router, Location], (rtr: Router, loc: Location) => {
router = rtr;
location = loc;
}));
@ -56,8 +58,8 @@ export function main() {
router.config([new Route({path: '/', component: DummyComponent})])
.then((_) => router.registerPrimaryOutlet(outlet))
.then((_) => {
expect(outlet.spy('activate')).toHaveBeenCalled();
expect(location.urlChanges).toEqual([]);
expect((<any>outlet).spy('activate')).toHaveBeenCalled();
expect((<SpyLocation>location).urlChanges).toEqual([]);
async.done();
});
}));
@ -70,8 +72,8 @@ export function main() {
.then((_) => router.config([new Route({path: '/a', component: DummyComponent})]))
.then((_) => router.navigateByUrl('/a'))
.then((_) => {
expect(outlet.spy('activate')).toHaveBeenCalled();
expect(location.urlChanges).toEqual(['/a']);
expect((<any>outlet).spy('activate')).toHaveBeenCalled();
expect((<SpyLocation>location).urlChanges).toEqual(['/a']);
async.done();
});
}));
@ -85,8 +87,8 @@ export function main() {
[new Route({path: '/a', component: DummyComponent, name: 'A'})]))
.then((_) => router.navigate(['/A']))
.then((_) => {
expect(outlet.spy('activate')).toHaveBeenCalled();
expect(location.urlChanges).toEqual(['/a']);
expect((<any>outlet).spy('activate')).toHaveBeenCalled();
expect((<SpyLocation>location).urlChanges).toEqual(['/a']);
async.done();
});
}));
@ -99,8 +101,8 @@ export function main() {
.then((_) => router.config([new Route({path: '/b', component: DummyComponent})]))
.then((_) => router.navigateByUrl('/b', true))
.then((_) => {
expect(outlet.spy('activate')).toHaveBeenCalled();
expect(location.urlChanges).toEqual([]);
expect((<any>outlet).spy('activate')).toHaveBeenCalled();
expect((<SpyLocation>location).urlChanges).toEqual([]);
async.done();
});
}));
@ -119,11 +121,11 @@ export function main() {
]))
.then((_) => {
router.subscribe((_) => {
expect(location.urlChanges).toEqual(['hash: a', 'replace: /b']);
expect((<SpyLocation>location).urlChanges).toEqual(['hash: a', 'replace: /b']);
async.done();
});
location.simulateHashChange('a');
(<SpyLocation>location).simulateHashChange('a');
});
}));
@ -135,11 +137,11 @@ export function main() {
.then((_) => router.config([new Route({path: '/a', component: DummyComponent})]))
.then((_) => {
router.subscribe((_) => {
expect(location.urlChanges).toEqual(['hash: a']);
expect((<SpyLocation>location).urlChanges).toEqual(['hash: a']);
async.done();
});
location.simulateHashChange('a');
(<SpyLocation>location).simulateHashChange('a');
});
}));
@ -149,11 +151,11 @@ export function main() {
router.registerPrimaryOutlet(outlet)
.then((_) => router.navigateByUrl('/a'))
.then((_) => {
expect(outlet.spy('activate')).not.toHaveBeenCalled();
expect((<any>outlet).spy('activate')).not.toHaveBeenCalled();
return router.config([new Route({path: '/a', component: DummyComponent})]);
})
.then((_) => {
expect(outlet.spy('activate')).toHaveBeenCalled();
expect((<any>outlet).spy('activate')).toHaveBeenCalled();
async.done();
});
}));
@ -193,7 +195,7 @@ export function main() {
var instruction = router.generate(['/FirstCmp']);
router.navigateByInstruction(instruction)
.then((_) => {
expect(outlet.spy('activate')).toHaveBeenCalled();
expect((<any>outlet).spy('activate')).toHaveBeenCalled();
async.done();
});
}));
@ -310,13 +312,13 @@ class DummyComponent {}
class DummyParentComp {
}
function makeDummyOutlet() {
function makeDummyOutlet(): RouterOutlet {
var ref = new SpyRouterOutlet();
ref.spy('canActivate').andCallFake((_) => PromiseWrapper.resolve(true));
ref.spy('routerCanReuse').andCallFake((_) => PromiseWrapper.resolve(false));
ref.spy('routerCanDeactivate').andCallFake((_) => PromiseWrapper.resolve(true));
ref.spy('activate').andCallFake((_) => PromiseWrapper.resolve(true));
return ref;
return <any>ref;
}
class AppCmp {}

View File

@ -21,6 +21,7 @@ import {isPresent, Type} from 'angular2/src/facade/lang';
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
import {MouseEvent, KeyboardEvent} from 'angular2/src/facade/browser';
import {KeyCodes} from 'angular2_material/src/core/key_codes';
import {PromiseCompleter} from 'angular2/src/facade/promise';
// TODO(jelbourn): Opener of dialog can control where it is rendered.
// TODO(jelbourn): body scrolling is disabled while dialog is open.
@ -61,7 +62,7 @@ export class MdDialog {
// First, load the MdDialogContainer, into which the given component will be loaded.
return this.componentLoader.loadNextToLocation(MdDialogContainer, elementRef)
.then(containerRef => {
.then /*<ComponentRef>*/ ((containerRef: ComponentRef) => {
// TODO(tbosch): clean this up when we have custom renderers
// (https://github.com/angular/angular/issues/1807)
// TODO(jelbourn): Don't use direct DOM access. Need abstraction to create an element
@ -84,7 +85,7 @@ export class MdDialog {
// Now load the given component into the MdDialogContainer.
return this.componentLoader.loadNextToLocation(type, containerRef.instance.contentRef,
bindings)
.then(contentRef => {
.then((contentRef: ComponentRef) => {
// Wrap both component refs for the container and the content so that we can return
// the `instance` of the content but the dispose method of the container back to the
@ -92,7 +93,7 @@ export class MdDialog {
dialogRef.contentRef = contentRef;
containerRef.instance.dialogRef = dialogRef;
backdropRefPromise.then(backdropRef => {
backdropRefPromise.then((backdropRef: ComponentRef) => {
dialogRef.whenClosed.then((_) => { backdropRef.dispose(); });
});
@ -104,7 +105,7 @@ export class MdDialog {
/** Loads the dialog backdrop (transparent overlay over the rest of the page). */
_openBackdrop(elementRef: ElementRef, bindings: ResolvedProvider[]): Promise<ComponentRef> {
return this.componentLoader.loadNextToLocation(MdBackdrop, elementRef, bindings)
.then((componentRef) => {
.then((componentRef: ComponentRef) => {
// TODO(tbosch): clean this up when we have custom renderers
// (https://github.com/angular/angular/issues/1807)
var backdropElement = componentRef.location.nativeElement;
@ -139,10 +140,10 @@ export class MdDialogRef {
isClosed: boolean;
// Deferred resolved when the dialog is closed. The promise for this deferred is publicly exposed.
whenClosedDeferred: any;
whenClosedDeferred: PromiseCompleter<any>;
// Deferred resolved when the content ComponentRef is set. Only used internally.
contentRefDeferred: any;
contentRefDeferred: PromiseCompleter<any>;
constructor() {
this._contentRef = null;

View File

@ -33,7 +33,9 @@ export class Runner {
this._defaultBindings = defaultBindings;
}
sample({id, execute, prepare, microMetrics, bindings}): Promise<SampleState> {
sample({id, execute, prepare, microMetrics, bindings}:
{id: string, execute?: any, prepare?: any, microMetrics?: any, bindings?: any}):
Promise<SampleState> {
var sampleBindings = [
_DEFAULT_PROVIDERS,
this._defaultBindings,

View File

@ -62,8 +62,8 @@ export class Sampler {
return loop(new SampleState([], null));
}
_iterate(lastState) {
var resultPromise;
_iterate(lastState): Promise<SampleState> {
var resultPromise: Promise<any>;
if (isPresent(this._prepare)) {
resultPromise = this._driver.waitFor(this._prepare);
} else {

View File

@ -39,7 +39,7 @@ export function main() {
captureFrames?: boolean,
receivedData?: boolean,
requestCount?: boolean
} = {}) {
} = {}): Metric {
commandLog = [];
if (isBlank(perfLogFeatures)) {
perfLogFeatures =
@ -384,7 +384,7 @@ export function main() {
aggregate(
[eventFactory.instant('frame', 4), eventFactory.markEnd('frameCapture', 5)],
{captureFrames: true}),
(err) => {
(err): any => {
expect(() => { throw err; })
.toThrowError('missing start event for frame capture');
async.done();
@ -396,7 +396,7 @@ export function main() {
aggregate(
[eventFactory.markStart('frameCapture', 3), eventFactory.instant('frame', 4)],
{captureFrames: true}),
(err) => {
(err): any => {
expect(() => { throw err; }).toThrowError('missing end event for frame capture');
async.done();
});
@ -410,7 +410,7 @@ export function main() {
eventFactory.markStart('frameCapture', 4)
],
{captureFrames: true}),
(err) => {
(err): any => {
expect(() => { throw err; })
.toThrowError('can capture frames only once per benchmark run');
async.done();
@ -424,12 +424,13 @@ export function main() {
.toThrowError(
'found start event for frame capture, but frame capture was not requested in benchpress');
async.done();
return null;
});
}));
it('should throw if frame capture is enabled, but nothing is captured',
inject([AsyncTestCompleter], (async) => {
PromiseWrapper.catchError(aggregate([], {captureFrames: true}), (err) => {
PromiseWrapper.catchError(aggregate([], {captureFrames: true}), (err): any => {
expect(() => { throw err; })
.toThrowError(
'frame capture requested in benchpress, but no start event was found');

View File

@ -31,7 +31,7 @@ export function main() {
var injector: Injector;
var runner;
function createRunner(defaultBindings = null) {
function createRunner(defaultBindings = null): Runner {
if (isBlank(defaultBindings)) {
defaultBindings = [];
}

View File

@ -31,7 +31,7 @@ export function main() {
var EMPTY_EXECUTE = () => {};
describe('sampler', () => {
var sampler;
var sampler: Sampler;
function createSampler({driver, metric, reporter, validator, prepare, execute}: {
driver?: any,

View File

@ -49,7 +49,7 @@ export function main() {
var normEvents = new TraceEventFactory('timeline', 'pid0');
function createExtension(perfRecords = null, userAgent = null,
messageMethod = 'Tracing.dataCollected') {
messageMethod = 'Tracing.dataCollected'): WebDriverExtension {
if (isBlank(perfRecords)) {
perfRecords = [];
}
@ -85,7 +85,7 @@ export function main() {
it('should mark the timeline via console.timeEnd()', inject([AsyncTestCompleter], (async) => {
createExtension()
.timeEnd('someName')
.timeEnd('someName', null)
.then((_) => {
expect(log).toEqual([['executeScript', `console.timeEnd('someName');`]]);
async.done();
@ -467,7 +467,7 @@ export function main() {
benchmarkEvents.instant('BenchmarkInstrumentation::ImplThreadRenderingStats',
1100, {'data': {'frame_count': 2}})
]).readPerfLog(),
(err) => {
(err): any => {
expect(() => { throw err; })
.toThrowError('multi-frame render stats not supported');
async.done();
@ -502,7 +502,7 @@ export function main() {
],
CHROME45_USER_AGENT, 'Tracing.bufferUsage')
.readPerfLog(),
(err) => {
(err): any => {
expect(() => { throw err; })
.toThrowError('The DevTools trace buffer filled during the test!');
async.done();

View File

@ -32,7 +32,7 @@ export function main() {
var normEvents = new TraceEventFactory('timeline', 'pid0');
function createExtension(perfRecords = null) {
function createExtension(perfRecords = null): WebDriverExtension {
if (isBlank(perfRecords)) {
perfRecords = [];
}
@ -61,7 +61,7 @@ export function main() {
it('should mark the timeline via console.timeEnd()', inject([AsyncTestCompleter], (async) => {
createExtension()
.timeEnd('someName')
.timeEnd('someName', null)
.then((_) => {
expect(log).toEqual([['executeScript', `console.timeEnd('someName');`]]);
async.done();

View File

@ -12,11 +12,12 @@ import {
import {Component, Directive, View, Host} from 'angular2/core';
import {RegExpWrapper, print, isPresent} from 'angular2/src/facade/lang';
import {AbstractControl} from 'angular2/common';
/**
* Custom validator.
*/
function creditCardValidator(c): {[key: string]: boolean} {
function creditCardValidator(c: AbstractControl): {[key: string]: boolean} {
if (isPresent(c.value) && RegExpWrapper.test(/^\d{16}$/g, c.value)) {
return null;
} else {

View File

@ -9,9 +9,9 @@ import {
RouteParams
} from 'angular2/router';
import * as db from './data';
import {ObservableWrapper, PromiseWrapper} from 'angular2/src/facade/async';
import {ListWrapper} from 'angular2/src/facade/collection';
import {PromiseWrapper} from 'angular2/src/facade/async';
import {isPresent, DateWrapper} from 'angular2/src/facade/lang';
import {PromiseCompleter} from 'angular2/src/facade/promise';
class InboxRecord {
id: string = '';
@ -60,31 +60,31 @@ class InboxRecord {
@Injectable()
class DbService {
getData(): Promise<any[]> {
var p = PromiseWrapper.completer();
var p = new PromiseCompleter<any[]>();
p.resolve(db.data);
return p.promise;
}
drafts(): Promise<any[]> {
return PromiseWrapper.then(this.getData(), (data: any[]) => {
return data.filter(record => isPresent(record['draft']) && record['draft'] == true);
});
return this.getData().then(
(data: any[]): any[] =>
data.filter(record => isPresent(record['draft']) && record['draft'] == true));
}
emails(): Promise<any[]> {
return PromiseWrapper.then(this.getData(), (data: any[]) => {
return data.filter(record => !isPresent(record['draft']));
});
return this.getData().then((data: any[]): any[] =>
data.filter(record => !isPresent(record['draft'])));
}
email(id): Promise<any> {
return PromiseWrapper.then(this.getData(), (data) => {
return PromiseWrapper.then(this.getData(), (data: any[]) => {
for (var i = 0; i < data.length; i++) {
var entry = data[i];
if (entry['id'] == id) {
return entry;
}
}
return null;
});
}
}
@ -109,16 +109,16 @@ class InboxCmp {
var sortType = params.get('sort');
var sortEmailsByDate = isPresent(sortType) && sortType == "date";
PromiseWrapper.then(db.emails(), emails => {
PromiseWrapper.then(db.emails(), (emails: any[]) => {
this.ready = true;
this.items = emails.map(data => new InboxRecord(data));
if (sortEmailsByDate) {
ListWrapper.sort(this.items,
(a, b) => DateWrapper.toMillis(DateWrapper.fromISOString(a.date)) <
DateWrapper.toMillis(DateWrapper.fromISOString(b.date)) ?
-1 :
1);
this.items.sort((a: InboxRecord, b: InboxRecord) =>
DateWrapper.toMillis(DateWrapper.fromISOString(a.date)) <
DateWrapper.toMillis(DateWrapper.fromISOString(b.date)) ?
-1 :
1);
}
});
}
@ -131,7 +131,7 @@ class DraftsCmp {
ready: boolean = false;
constructor(public router: Router, db: DbService) {
PromiseWrapper.then(db.drafts(), (drafts) => {
PromiseWrapper.then(db.drafts(), (drafts: any[]) => {
this.ready = true;
this.items = drafts.map(data => new InboxRecord(data));
});

View File

@ -8,7 +8,7 @@ import {Store, Todo, TodoFactory} from './services/TodoStore';
class TodoApp {
todoEdit: Todo = null;
constructor(public todoStore: Store, public factory: TodoFactory) {}
constructor(public todoStore: Store<Todo>, public factory: TodoFactory) {}
enterTodo(inputElement): void {
this.addTodo(inputElement.value);

View File

@ -2,7 +2,7 @@ import {Injectable} from 'angular2/core';
import {ListWrapper, Predicate} from 'angular2/src/facade/collection';
// base model for RecordStore
export class KeyModel {
export abstract class KeyModel {
constructor(public key: number) {}
}
@ -23,19 +23,19 @@ export class TodoFactory {
// Store manages any generic item that inherits from KeyModel
@Injectable()
export class Store {
list: KeyModel[] = [];
export class Store<T extends KeyModel> {
list: T[] = [];
add(record: KeyModel): void { this.list.push(record); }
add(record: T): void { this.list.push(record); }
remove(record: KeyModel): void { this._spliceOut(record); }
remove(record: T): void { this._spliceOut(record); }
removeBy(callback: Predicate<KeyModel>): void {
removeBy(callback: Predicate<T>): void {
var records = this.list.filter(callback);
ListWrapper.removeAll(this.list, records);
}
private _spliceOut(record: KeyModel) {
private _spliceOut(record: T) {
var i = this._indexFor(record);
if (i > -1) {
return ListWrapper.splice(this.list, i, 1)[0];
@ -43,5 +43,5 @@ export class Store {
return null;
}
private _indexFor(record: KeyModel) { return this.list.indexOf(record); }
private _indexFor(record: T) { return this.list.indexOf(record); }
}

View File

@ -225,7 +225,7 @@ class _CodegenState {
List<String> codes = [];
_endOfBlockIdxs.clear();
ListWrapper.forEachWithIndex(eb.records, (_, i) {
ListWrapper.forEachWithIndex(eb.records, (ProtoRecord _, int i) {
var code;
var r = eb.records[i];

View File

@ -1887,7 +1887,7 @@
"version": "4.0.1"
},
"dart-style": {
"version": "0.2.6"
"version": "0.2.7"
},
"dart2jsaas": {
"version": "0.0.16",
@ -5356,7 +5356,7 @@
}
},
"ts2dart": {
"version": "0.7.24",
"version": "0.7.31",
"dependencies": {
"source-map": {
"version": "0.4.4"
@ -5839,5 +5839,5 @@
}
},
"name": "angular-srcs",
"version": "2.0.0-beta.6"
"version": "2.0.0-beta.8"
}

15
npm-shrinkwrap.json generated
View File

@ -1,6 +1,6 @@
{
"name": "angular-srcs",
"version": "2.0.0-beta.6",
"version": "2.0.0-beta.8",
"dependencies": {
"abbrev": {
"version": "1.0.7",
@ -2961,9 +2961,9 @@
"resolved": "https://registry.npmjs.org/dargs/-/dargs-4.0.1.tgz"
},
"dart-style": {
"version": "0.2.6",
"version": "0.2.7",
"from": "dart-style@>=0.2.6 <0.3.0",
"resolved": "https://registry.npmjs.org/dart-style/-/dart-style-0.2.6.tgz"
"resolved": "https://registry.npmjs.org/dart-style/-/dart-style-0.2.7.tgz"
},
"dart2jsaas": {
"version": "0.0.16",
@ -8536,9 +8536,9 @@
}
},
"ts2dart": {
"version": "0.7.24",
"from": "ts2dart@0.7.24",
"resolved": "https://registry.npmjs.org/ts2dart/-/ts2dart-0.7.24.tgz",
"version": "0.7.31",
"from": "ts2dart@0.7.31",
"resolved": "https://registry.npmjs.org/ts2dart/-/ts2dart-0.7.31.tgz",
"dependencies": {
"source-map": {
"version": "0.4.4",
@ -9310,7 +9310,8 @@
},
"zone.js": {
"version": "0.5.15",
"from": "zone.js@0.5.15"
"from": "zone.js@0.5.15",
"resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.5.15.tgz"
}
}
}

View File

@ -112,7 +112,7 @@
"systemjs-builder": "^0.10.3",
"through2": "^0.6.5",
"ts-api-guardian": "0.0.2",
"ts2dart": "^0.7.22",
"ts2dart": "^0.7.31",
"tsd": "^0.6.5-beta",
"tslint": "^3.2.1",
"typescript": "^1.7.3",

View File

@ -11,10 +11,10 @@ source $SCRIPT_DIR/env_dart.sh
cd $SCRIPT_DIR/../..
# Variables
DDC_TOTAL_WARNING_CAP="1000"
DDC_TOTAL_ERROR_CAP="11"
DDC_TOTAL_WARNING_CAP="210"
DDC_TOTAL_ERROR_CAP="0"
DDC_DIR=`pwd`/tmp/dev_compiler
DDC_VERSION="0.1.14"
DDC_VERSION="0.1.20"
# Get DDC
mkdir -p tmp
@ -78,21 +78,27 @@ then
fi
cat $LOG_FILE
WARNING_COUNT=`cat $LOG_FILE | wc -l | sed -e 's/^[[:space:]]*//'`
EXIT_CODE=0
# TODO remove `grep -v template.dart` after Tobias new compiler lands.
WARNING_COUNT=$(cat $LOG_FILE | grep -E '^warning.*' | grep -v template.dart | wc -l | sed -e 's/^[[:space:]]*//' || true)
ERROR_COUNT=$(cat $LOG_FILE | grep -E '^severe.*' | wc -l | sed -e 's/^[[:space:]]*//' || true)
if [[ "$ERROR_COUNT" -gt "$DDC_TOTAL_ERROR_CAP" ]]
then
echo "Found severe errors in angular2 package"
EXIT_CODE=1
fi
if [[ "$WARNING_COUNT" -gt "$DDC_TOTAL_WARNING_CAP" ]]
then
echo "Too many warnings: $WARNING_COUNT"
exit 1
EXIT_CODE=1
else
echo "Warning count ok"
fi
ERROR_COUNT=`cat $LOG_FILE | grep -E '^severe.*' | wc -l | sed -e 's/^[[:space:]]*//'`
if [[ "$ERROR_COUNT" -gt "$DDC_TOTAL_ERROR_CAP" ]]
then
echo "Found severe errors in angular2 package"
exit 1
fi
echo 'Dart DDC build finished'
exit $EXIT_CODE

View File

@ -66,12 +66,7 @@ if [[ -z $ENV_SET ]]; then
fi
fi
case "$PLATFORM" in
(Linux) export DART_SDK_LIB_SEARCH_PATH="$DART_SDK" ;;
(Darwin) export DART_SDK_LIB_SEARCH_PATH="$DART_SDK/libexec" ;;
(*) echo Unsupported platform $PLATFORM. Exiting ... >&2 ; exit 3 ;;
esac
export DART_SDK_LIB_SEARCH_PATH="$DART_SDK"
export DART_SDK
export DARTSDK
export DART

View File

@ -382,7 +382,7 @@ const CORE = [
'Reflector.isReflectionEnabled():boolean',
'Reflector.listUnusedKeys():any[]',
'Reflector.method(name:string):MethodFn',
'Reflector.parameters(typeOrFunc:any):any[]',
'Reflector.parameters(typeOrFunc:any):any[][]',
'Reflector.propMetadata(typeOrFunc:any):{[key:string]:any[]}',
'Reflector.reflectionCapabilities:PlatformReflectionCapabilities',
'Reflector.registerFunction(func:Function, funcInfo:ReflectionInfo):void',
@ -555,7 +555,7 @@ const CORE = [
const COMMON = [
'AbstractControl',
'AbstractControl.constructor(validator:Function, asyncValidator:Function)',
'AbstractControl.constructor(validator:ValidatorFn, asyncValidator:AsyncValidatorFn)',
'AbstractControl.dirty:boolean',
'AbstractControl.errors:{[key:string]:any}',
'AbstractControl.find(path:Array<string|number>|string):AbstractControl',
@ -599,12 +599,12 @@ const COMMON = [
'CheckboxControlValueAccessor.registerOnTouched(fn:() => {}):void',
'CheckboxControlValueAccessor.writeValue(value:any):void',
'Control',
'Control.constructor(value:any, validator:Function, asyncValidator:Function)',
'Control.constructor(value:any, validator:ValidatorFn, asyncValidator:AsyncValidatorFn)',
'Control.registerOnChange(fn:Function):void',
'Control.updateValue(value:any, {onlySelf,emitEvent,emitModelToViewChange}:{onlySelf?:boolean, emitEvent?:boolean, emitModelToViewChange?:boolean}):void',
'ControlArray',
'ControlArray.at(index:number):AbstractControl',
'ControlArray.constructor(controls:AbstractControl[], validator:Function, asyncValidator:Function)',
'ControlArray.constructor(controls:AbstractControl[], validator:ValidatorFn, asyncValidator:AsyncValidatorFn)',
'ControlArray.insert(index:number, control:AbstractControl):void',
'ControlArray.length:number',
'ControlArray.push(control:AbstractControl):void',
@ -615,7 +615,7 @@ const COMMON = [
'ControlContainer.path:string[]',
'ControlGroup',
'ControlGroup.addControl(name:string, control:AbstractControl):void',
'ControlGroup.constructor(controls:{[key:string]:AbstractControl}, optionals:{[key:string]:boolean}, validator:Function, asyncValidator:Function)',
'ControlGroup.constructor(controls:{[key:string]:AbstractControl}, optionals:{[key:string]:boolean}, validator:ValidatorFn, asyncValidator:AsyncValidatorFn)',
'ControlGroup.contains(controlName:string):boolean',
'ControlGroup.exclude(controlName:string):void',
'ControlGroup.include(controlName:string):void',
@ -647,8 +647,8 @@ const COMMON = [
'Form.removeControlGroup(dir:NgControlGroup):void',
'Form.updateModel(dir:NgControl, value:any):void',
'FormBuilder',
'FormBuilder.array(controlsConfig:any[], validator:Function, asyncValidator:Function):ControlArray',
'FormBuilder.control(value:Object, validator:Function, asyncValidator:Function):Control',
'FormBuilder.array(controlsConfig:any[], validator:ValidatorFn, asyncValidator:AsyncValidatorFn):ControlArray',
'FormBuilder.control(value:Object, validator:ValidatorFn, asyncValidator:AsyncValidatorFn):Control',
'FormBuilder.group(controlsConfig:{[key:string]:any}, extra:{[key:string]:any}):ControlGroup',
'I18nPluralPipe',
'I18nPluralPipe.transform(value:number, args:any[]):string',
@ -660,10 +660,10 @@ const COMMON = [
'LowerCasePipe.transform(value:string, args:any[]):string',
'MaxLengthValidator',
'MaxLengthValidator.constructor(maxLength:string)',
'MaxLengthValidator.validate(c:Control):{[key:string]:any}',
'MaxLengthValidator.validate(c:AbstractControl):{[key:string]:any}',
'MinLengthValidator',
'MinLengthValidator.constructor(minLength:string)',
'MinLengthValidator.validate(c:Control):{[key:string]:any}',
'MinLengthValidator.validate(c:AbstractControl):{[key:string]:any}',
'NgClass',
'NgClass.constructor(_iterableDiffers:IterableDiffers, _keyValueDiffers:KeyValueDiffers, _ngEl:ElementRef, _renderer:Renderer)',
'NgClass.initialClasses=(v:string)',
@ -671,22 +671,22 @@ const COMMON = [
'NgClass.ngOnDestroy():void',
'NgClass.rawClass=(v:string|string[]|Set<string>|{[key:string]:any})',
'NgControl',
'NgControl.asyncValidator:Function',
'NgControl.asyncValidator:AsyncValidatorFn',
'NgControl.name:string',
'NgControl.validator:Function',
'NgControl.validator:ValidatorFn',
'NgControl.valueAccessor:ControlValueAccessor',
'NgControl.viewToModelUpdate(newValue:any):void',
'NgControlGroup',
'NgControlGroup.asyncValidator:Function',
'NgControlGroup.asyncValidator:AsyncValidatorFn',
'NgControlGroup.constructor(parent:ControlContainer, _validators:any[], _asyncValidators:any[])',
'NgControlGroup.control:ControlGroup',
'NgControlGroup.formDirective:Form',
'NgControlGroup.ngOnDestroy():void',
'NgControlGroup.ngOnInit():void',
'NgControlGroup.path:string[]',
'NgControlGroup.validator:Function',
'NgControlGroup.validator:ValidatorFn',
'NgControlName',
'NgControlName.asyncValidator:Function',
'NgControlName.asyncValidator:AsyncValidatorFn',
'NgControlName.constructor(_parent:ControlContainer, _validators:any[], _asyncValidators:any[], valueAccessors:ControlValueAccessor[])',
'NgControlName.control:Control',
'NgControlName.formDirective:any',
@ -695,7 +695,7 @@ const COMMON = [
'NgControlName.ngOnDestroy():void',
'NgControlName.path:string[]',
'NgControlName.update:any',
'NgControlName.validator:Function',
'NgControlName.validator:ValidatorFn',
'NgControlName.viewModel:any',
'NgControlName.viewToModelUpdate(newValue:any):void',
'NgControlStatus',
@ -729,7 +729,7 @@ const COMMON = [
'NgForm.removeControlGroup(dir:NgControlGroup):void',
'NgForm.updateModel(dir:NgControl, value:any):void',
'NgFormControl',
'NgFormControl.asyncValidator:Function',
'NgFormControl.asyncValidator:AsyncValidatorFn',
'NgFormControl.constructor(_validators:any[], _asyncValidators:any[], valueAccessors:ControlValueAccessor[])',
'NgFormControl.control:Control',
'NgFormControl.form:Control',
@ -737,7 +737,7 @@ const COMMON = [
'NgFormControl.ngOnChanges(changes:{[key:string]:SimpleChange}):void',
'NgFormControl.path:string[]',
'NgFormControl.update:any',
'NgFormControl.validator:Function',
'NgFormControl.validator:ValidatorFn',
'NgFormControl.viewModel:any',
'NgFormControl.viewToModelUpdate(newValue:any):void',
'NgFormModel',
@ -761,14 +761,14 @@ const COMMON = [
'NgIf.constructor(_viewContainer:ViewContainerRef, _templateRef:TemplateRef)',
'NgIf.ngIf=(newCondition:any)',
'NgModel',
'NgModel.asyncValidator:Function',
'NgModel.asyncValidator:AsyncValidatorFn',
'NgModel.constructor(_validators:any[], _asyncValidators:any[], valueAccessors:ControlValueAccessor[])',
'NgModel.control:Control',
'NgModel.model:any',
'NgModel.ngOnChanges(changes:{[key:string]:SimpleChange}):any',
'NgModel.path:string[]',
'NgModel.update:any',
'NgModel.validator:Function',
'NgModel.validator:ValidatorFn',
'NgModel.viewModel:any',
'NgModel.viewToModelUpdate(newValue:any):void',
'NgSelectOption',
@ -786,7 +786,7 @@ const COMMON = [
'NumberPipe',
'PatternValidator',
'PatternValidator.constructor(pattern:string)',
'PatternValidator.validate(c:Control):{[key:string]:any}',
'PatternValidator.validate(c:AbstractControl):{[key:string]:any}',
'PercentPipe',
'PercentPipe.transform(value:any, args:any[]):string',
'ReplacePipe',
@ -805,15 +805,15 @@ const COMMON = [
'UpperCasePipe',
'UpperCasePipe.transform(value:string, args:any[]):string',
'Validator',
'Validator.validate(c:Control):{[key:string]:any}',
'Validator.validate(c:AbstractControl):{[key:string]:any}',
'Validators',
'Validators.compose(validators:Function[]):Function',
'Validators.composeAsync(validators:Function[]):Function',
'Validators.maxLength(maxLength:number):Function',
'Validators.minLength(minLength:number):Function',
'Validators.nullValidator(c:any):{[key:string]:boolean}',
'Validators.pattern(pattern:string):Function',
'Validators.required(control:Control):{[key:string]:boolean}',
'Validators.compose(validators:ValidatorFn[]):ValidatorFn',
'Validators.composeAsync(validators:AsyncValidatorFn[]):AsyncValidatorFn',
'Validators.maxLength(maxLength:number):ValidatorFn',
'Validators.minLength(minLength:number):ValidatorFn',
'Validators.nullValidator(c:AbstractControl):{[key:string]:boolean}',
'Validators.pattern(pattern:string):ValidatorFn',
'Validators.required(control:AbstractControl):{[key:string]:boolean}',
'RadioButtonState',
'RadioButtonState.constructor(checked:boolean, value:string)',
'const COMMON_DIRECTIVES:Type[][]',