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); });
}
}