refactor: core, http & platform-webworker to remove public private class separation (#19143)

The private classes `ApplicationRef_`, `PlatformRef_`, `JSONPConnection_`, `JSONPBackend_`, `ClientMessageBrokerFactory_`, `ServiceMessageBroker_`, `ClientMessageBroker_` and `ServiceMessageBrokerFactory_` have been removed and merged into their public equivalents.

The size of the minified umd bundles have been slightly decreased:
| package            | before     | after      |
| -------------------|------------|------------|
| core               | 217.791 kb | 217.144 kb |
| http               | 33.260 kb  | 32.838 kb  | 
| platform-webworker | 56.015 kb  | 54.933 kb  |
PR Close #19143
This commit is contained in:
Olivier Combe 2017-09-12 20:45:02 +02:00 committed by Matias Niemelä
parent 0c44e733ad
commit b6431c60e6
19 changed files with 252 additions and 326 deletions

View File

@ -7,7 +7,7 @@
*/
import {ApplicationInitStatus} from './application_init';
import {ApplicationRef, ApplicationRef_} from './application_ref';
import {ApplicationRef} from './application_ref';
import {APP_ID_RANDOM_PROVIDER} from './application_tokens';
import {IterableDiffers, KeyValueDiffers, defaultIterableDiffers, defaultKeyValueDiffers} from './change_detection/change_detection';
import {Inject, Optional, SkipSelf} from './di/metadata';
@ -35,8 +35,7 @@ export function _localeFactory(locale?: string): string {
*/
@NgModule({
providers: [
ApplicationRef_,
{provide: ApplicationRef, useExisting: ApplicationRef_},
ApplicationRef,
ApplicationInitStatus,
Compiler,
APP_ID_RANDOM_PROVIDER,

View File

@ -168,7 +168,14 @@ export function getPlatform(): PlatformRef|null {
*
* @stable
*/
export abstract class PlatformRef {
export class PlatformRef {
private _modules: NgModuleRef<any>[] = [];
private _destroyListeners: Function[] = [];
private _destroyed: boolean = false;
/** @internal */
constructor(private _injector: Injector) {}
/**
* Creates an instance of an `@NgModule` for the given platform
* for offline compilation.
@ -192,93 +199,6 @@ export abstract class PlatformRef {
*
* @experimental APIs related to application bootstrap are currently under review.
*/
abstract bootstrapModuleFactory<M>(moduleFactory: NgModuleFactory<M>): Promise<NgModuleRef<M>>;
/**
* Creates an instance of an `@NgModule` for a given platform using the given runtime compiler.
*
* ## Simple Example
*
* ```typescript
* @NgModule({
* imports: [BrowserModule]
* })
* class MyModule {}
*
* let moduleRef = platformBrowser().bootstrapModule(MyModule);
* ```
* @stable
*/
abstract bootstrapModule<M>(
moduleType: Type<M>,
compilerOptions?: CompilerOptions|CompilerOptions[]): Promise<NgModuleRef<M>>;
/**
* Register a listener to be called when the platform is disposed.
*/
abstract onDestroy(callback: () => void): void;
/**
* Retrieve the platform {@link Injector}, which is the parent injector for
* every Angular application on the page and provides singleton providers.
*/
abstract get injector(): Injector;
/**
* Destroy the Angular platform and all Angular applications on the page.
*/
abstract destroy(): void;
abstract get destroyed(): boolean;
}
function _callAndReportToErrorHandler(
errorHandler: ErrorHandler, ngZone: NgZone, callback: () => any): any {
try {
const result = callback();
if (isPromise(result)) {
return result.catch((e: any) => {
ngZone.runOutsideAngular(() => errorHandler.handleError(e));
// rethrow as the exception handler might not do it
throw e;
});
}
return result;
} catch (e) {
ngZone.runOutsideAngular(() => errorHandler.handleError(e));
// rethrow as the exception handler might not do it
throw e;
}
}
/**
* workaround https://github.com/angular/tsickle/issues/350
* @suppress {checkTypes}
*/
@Injectable()
export class PlatformRef_ extends PlatformRef {
private _modules: NgModuleRef<any>[] = [];
private _destroyListeners: Function[] = [];
private _destroyed: boolean = false;
constructor(private _injector: Injector) { super(); }
onDestroy(callback: () => void): void { this._destroyListeners.push(callback); }
get injector(): Injector { return this._injector; }
get destroyed() { return this._destroyed; }
destroy() {
if (this._destroyed) {
throw new Error('The platform has already been destroyed!');
}
this._modules.slice().forEach(module => module.destroy());
this._destroyListeners.forEach(listener => listener());
this._destroyed = true;
}
bootstrapModuleFactory<M>(moduleFactory: NgModuleFactory<M>): Promise<NgModuleRef<M>> {
return this._bootstrapModuleFactoryWithZone(moduleFactory);
}
@ -314,6 +234,21 @@ export class PlatformRef_ extends PlatformRef {
});
}
/**
* Creates an instance of an `@NgModule` for a given platform using the given runtime compiler.
*
* ## Simple Example
*
* ```typescript
* @NgModule({
* imports: [BrowserModule]
* })
* class MyModule {}
*
* let moduleRef = platformBrowser().bootstrapModule(MyModule);
* ```
* @stable
*/
bootstrapModule<M>(moduleType: Type<M>, compilerOptions: CompilerOptions|CompilerOptions[] = []):
Promise<NgModuleRef<M>> {
return this._bootstrapModuleWithZone(moduleType, compilerOptions);
@ -343,6 +278,51 @@ export class PlatformRef_ extends PlatformRef {
}
this._modules.push(moduleRef);
}
/**
* Register a listener to be called when the platform is disposed.
*/
onDestroy(callback: () => void): void { this._destroyListeners.push(callback); }
/**
* 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 this._injector; }
/**
* Destroy the Angular platform and all Angular applications on the page.
*/
destroy() {
if (this._destroyed) {
throw new Error('The platform has already been destroyed!');
}
this._modules.slice().forEach(module => module.destroy());
this._destroyListeners.forEach(listener => listener());
this._destroyed = true;
}
get destroyed() { return this._destroyed; }
}
function _callAndReportToErrorHandler(
errorHandler: ErrorHandler, ngZone: NgZone, callback: () => any): any {
try {
const result = callback();
if (isPromise(result)) {
return result.catch((e: any) => {
ngZone.runOutsideAngular(() => errorHandler.handleError(e));
// rethrow as the exception handler might not do it
throw e;
});
}
return result;
} catch (e) {
ngZone.runOutsideAngular(() => errorHandler.handleError(e));
// rethrow as the exception handler might not do it
throw e;
}
}
/**
@ -350,81 +330,10 @@ export class PlatformRef_ extends PlatformRef {
*
* @stable
*/
export abstract class ApplicationRef {
/**
* Bootstrap a new component at the root level of the application.
*
* ### Bootstrap process
*
* When bootstrapping a new root component into an application, Angular mounts the
* specified application component onto DOM elements identified by the [componentType]'s
* selector and kicks off automatic change detection to finish initializing the component.
*
* Optionally, a component can be mounted onto a DOM element that does not match the
* [componentType]'s selector.
*
* ### Example
* {@example core/ts/platform/platform.ts region='longform'}
*/
abstract bootstrap<C>(
componentFactory: ComponentFactory<C>|Type<C>,
rootSelectorOrNode?: string|any): ComponentRef<C>;
/**
* Invoke this method to explicitly process change detection and its side-effects.
*
* In development mode, `tick()` also performs a second change detection cycle to ensure that no
* further changes are detected. If additional changes are picked up during this second cycle,
* bindings in the app have side-effects that cannot be resolved in a single change detection
* pass.
* In this case, Angular throws an error, since an Angular application can only have one change
* detection pass during which all change detection must complete.
*/
abstract tick(): void;
/**
* Get a list of component types registered to this application.
* This list is populated even before the component is created.
*/
abstract get componentTypes(): Type<any>[];
/**
* Get a list of components registered to this application.
*/
abstract get components(): ComponentRef<any>[];
/**
* Attaches a view so that it will be dirty checked.
* The view will be automatically detached when it is destroyed.
* This will throw if the view is already attached to a ViewContainer.
*/
abstract attachView(view: ViewRef): void;
/**
* Detaches a view from dirty checking again.
*/
abstract detachView(view: ViewRef): void;
/**
* Returns the number of attached views.
*/
abstract get viewCount(): number;
/**
* Returns an Observable that indicates when the application is stable or unstable.
*/
abstract get isStable(): Observable<boolean>;
}
/**
* workaround https://github.com/angular/tsickle/issues/350
* @suppress {checkTypes}
*/
@Injectable()
export class ApplicationRef_ extends ApplicationRef {
export class ApplicationRef {
/** @internal */
static _tickScope: WtfScopeFn = wtfCreateScope('ApplicationRef#tick()');
private _bootstrapListeners: ((compRef: ComponentRef<any>) => void)[] = [];
private _rootComponents: ComponentRef<any>[] = [];
private _rootComponentTypes: Type<any>[] = [];
@ -434,12 +343,12 @@ export class ApplicationRef_ extends ApplicationRef {
private _isStable: Observable<boolean>;
private _stable = true;
/** @internal */
constructor(
private _zone: NgZone, private _console: Console, private _injector: Injector,
private _exceptionHandler: ErrorHandler,
private _componentFactoryResolver: ComponentFactoryResolver,
private _initStatus: ApplicationInitStatus) {
super();
this._enforceNoNewChanges = isDevMode();
this._zone.onMicrotaskEmpty.subscribe(
@ -491,18 +400,21 @@ export class ApplicationRef_ extends ApplicationRef {
this._isStable = merge(isCurrentlyStable, share.call(isStable));
}
attachView(viewRef: ViewRef): void {
const view = (viewRef as InternalViewRef);
this._views.push(view);
view.attachToAppRef(this);
}
detachView(viewRef: ViewRef): void {
const view = (viewRef as InternalViewRef);
remove(this._views, view);
view.detachFromAppRef();
}
/**
* Bootstrap a new component at the root level of the application.
*
* ### Bootstrap process
*
* When bootstrapping a new root component into an application, Angular mounts the
* specified application component onto DOM elements identified by the [componentType]'s
* selector and kicks off automatic change detection to finish initializing the component.
*
* Optionally, a component can be mounted onto a DOM element that does not match the
* [componentType]'s selector.
*
* ### Example
* {@example core/ts/platform/platform.ts region='longform'}
*/
bootstrap<C>(componentOrFactory: ComponentFactory<C>|Type<C>, rootSelectorOrNode?: string|any):
ComponentRef<C> {
if (!this._initStatus.done) {
@ -540,27 +452,22 @@ export class ApplicationRef_ extends ApplicationRef {
return compRef;
}
private _loadComponent(componentRef: ComponentRef<any>): void {
this.attachView(componentRef.hostView);
this.tick();
this._rootComponents.push(componentRef);
// Get the listeners lazily to prevent DI cycles.
const listeners =
this._injector.get(APP_BOOTSTRAP_LISTENER, []).concat(this._bootstrapListeners);
listeners.forEach((listener) => listener(componentRef));
}
private _unloadComponent(componentRef: ComponentRef<any>): void {
this.detachView(componentRef.hostView);
remove(this._rootComponents, componentRef);
}
/**
* Invoke this method to explicitly process change detection and its side-effects.
*
* In development mode, `tick()` also performs a second change detection cycle to ensure that no
* further changes are detected. If additional changes are picked up during this second cycle,
* bindings in the app have side-effects that cannot be resolved in a single change detection
* pass.
* In this case, Angular throws an error, since an Angular application can only have one change
* detection pass during which all change detection must complete.
*/
tick(): void {
if (this._runningTick) {
throw new Error('ApplicationRef.tick is called recursively');
}
const scope = ApplicationRef_._tickScope();
const scope = ApplicationRef._tickScope();
try {
this._runningTick = true;
this._views.forEach((view) => view.detectChanges());
@ -576,17 +483,66 @@ export class ApplicationRef_ extends ApplicationRef {
}
}
/**
* Get a list of component types registered to this application.
* This list is populated even before the component is created.
*/
get componentTypes(): Type<any>[] { return this._rootComponentTypes; }
/**
* Get a list of components registered to this application.
*/
get components(): ComponentRef<any>[] { return this._rootComponents; }
/**
* Attaches a view so that it will be dirty checked.
* The view will be automatically detached when it is destroyed.
* This will throw if the view is already attached to a ViewContainer.
*/
attachView(viewRef: ViewRef): void {
const view = (viewRef as InternalViewRef);
this._views.push(view);
view.attachToAppRef(this);
}
/**
* Detaches a view from dirty checking again.
*/
detachView(viewRef: ViewRef): void {
const view = (viewRef as InternalViewRef);
remove(this._views, view);
view.detachFromAppRef();
}
private _loadComponent(componentRef: ComponentRef<any>): void {
this.attachView(componentRef.hostView);
this.tick();
this._rootComponents.push(componentRef);
// Get the listeners lazily to prevent DI cycles.
const listeners =
this._injector.get(APP_BOOTSTRAP_LISTENER, []).concat(this._bootstrapListeners);
listeners.forEach((listener) => listener(componentRef));
}
private _unloadComponent(componentRef: ComponentRef<any>): void {
this.detachView(componentRef.hostView);
remove(this._rootComponents, componentRef);
}
/** @internal */
ngOnDestroy() {
// TODO(alxhub): Dispose of the NgZone.
this._views.slice().forEach((view) => view.destroy());
}
/**
* Returns the number of attached views.
*/
get viewCount() { return this._views.length; }
get componentTypes(): Type<any>[] { return this._rootComponentTypes; }
get components(): ComponentRef<any>[] { return this._rootComponents; }
/**
* Returns an Observable that indicates when the application is stable or unstable.
*/
get isStable(): Observable<boolean> { return this._isStable; }
}

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {PlatformRef, PlatformRef_, createPlatformFactory} from './application_ref';
import {PlatformRef, createPlatformFactory} from './application_ref';
import {PLATFORM_ID} from './application_tokens';
import {Console} from './console';
import {Injector, StaticProvider} from './di';
@ -15,8 +15,7 @@ import {TestabilityRegistry} from './testability/testability';
const _CORE_PLATFORM_PROVIDERS: StaticProvider[] = [
// Set a default platform name for platforms that don't set it explicitly.
{provide: PLATFORM_ID, useValue: 'unknown'},
{provide: PlatformRef_, deps: [Injector]},
{provide: PlatformRef, useExisting: PlatformRef_},
{provide: PlatformRef, deps: [Injector]},
{provide: TestabilityRegistry, deps: []},
{provide: Console, deps: []},
];

View File

@ -7,10 +7,9 @@
*/
import {APP_BOOTSTRAP_LISTENER, APP_INITIALIZER, Compiler, CompilerFactory, Component, NgModule, NgZone, PlatformRef, TemplateRef, Type, ViewChild, ViewContainerRef} from '@angular/core';
import {ApplicationRef, ApplicationRef_} from '@angular/core/src/application_ref';
import {ApplicationRef} from '@angular/core/src/application_ref';
import {ErrorHandler} from '@angular/core/src/error_handler';
import {ComponentRef} from '@angular/core/src/linker/component_factory';
import {TestComponentRenderer} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {DOCUMENT} from '@angular/platform-browser/src/dom/dom_tokens';
@ -173,7 +172,7 @@ export function main() {
});
it('should be called when a component is bootstrapped',
inject([ApplicationRef], (ref: ApplicationRef_) => {
inject([ApplicationRef], (ref: ApplicationRef) => {
createRootEl();
const compRef = ref.bootstrap(SomeComponent);
expect(capturedCompRefs).toEqual([compRef]);
@ -188,7 +187,7 @@ export function main() {
{provide: APP_INITIALIZER, useValue: () => new Promise(() => {}), multi: true}
]
},
inject([ApplicationRef], (ref: ApplicationRef_) => {
inject([ApplicationRef], (ref: ApplicationRef) => {
createRootEl();
expect(() => ref.bootstrap(SomeComponent))
.toThrowError(

View File

@ -22,11 +22,16 @@ const JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';
const JSONP_ERR_WRONG_METHOD = 'JSONP requests must use GET request method.';
/**
* Abstract base class for an in-flight JSONP request.
* Base class for an in-flight JSONP request.
*
* @deprecated use @angular/common/http instead
*/
export abstract class JSONPConnection implements Connection {
export class JSONPConnection implements Connection {
private _id: string;
private _script: Element;
private _responseData: any;
private _finished: boolean = false;
/**
* The {@link ReadyState} of this request.
*/
@ -42,22 +47,9 @@ export abstract class JSONPConnection implements Connection {
*/
response: Observable<Response>;
/**
* Callback called when the JSONP request completes, to notify the application
* of the new data.
*/
abstract finished(data?: any): void;
}
export class JSONPConnection_ extends JSONPConnection {
private _id: string;
private _script: Element;
private _responseData: any;
private _finished: boolean = false;
/** @internal */
constructor(
req: Request, private _dom: BrowserJsonp, private baseResponseOptions?: ResponseOptions) {
super();
if (req.method !== RequestMethod.Get) {
throw new TypeError(JSONP_ERR_WRONG_METHOD);
}
@ -129,6 +121,10 @@ export class JSONPConnection_ extends JSONPConnection {
});
}
/**
* Callback called when the JSONP request completes, to notify the application
* of the new data.
*/
finished(data?: any) {
// Don't leak connections
this._finished = true;
@ -143,15 +139,14 @@ export class JSONPConnection_ extends JSONPConnection {
*
* @deprecated use @angular/common/http instead
*/
export abstract class JSONPBackend extends ConnectionBackend {}
@Injectable()
export class JSONPBackend_ extends JSONPBackend {
export class JSONPBackend extends ConnectionBackend {
/** @internal */
constructor(private _browserJSONP: BrowserJsonp, private _baseResponseOptions: ResponseOptions) {
super();
}
createConnection(request: Request): JSONPConnection {
return new JSONPConnection_(request, this._browserJSONP, this._baseResponseOptions);
return new JSONPConnection(request, this._browserJSONP, this._baseResponseOptions);
}
}

View File

@ -16,7 +16,7 @@ import {NgModule} from '@angular/core';
import {BrowserJsonp} from './backends/browser_jsonp';
import {BrowserXhr} from './backends/browser_xhr';
import {JSONPBackend, JSONPBackend_} from './backends/jsonp_backend';
import {JSONPBackend} from './backends/jsonp_backend';
import {CookieXSRFStrategy, XHRBackend} from './backends/xhr_backend';
import {BaseRequestOptions, RequestOptions} from './base_request_options';
import {BaseResponseOptions, ResponseOptions} from './base_response_options';
@ -70,7 +70,7 @@ export class HttpModule {
BrowserJsonp,
{provide: RequestOptions, useClass: BaseRequestOptions},
{provide: ResponseOptions, useClass: BaseResponseOptions},
{provide: JSONPBackend, useClass: JSONPBackend_},
JSONPBackend,
],
})
export class JsonpModule {

View File

@ -10,7 +10,7 @@ import {Injector} from '@angular/core';
import {AsyncTestCompleter, SpyObject, afterEach, beforeEach, describe, inject, it} from '@angular/core/testing/src/testing_internal';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {BrowserJsonp} from '../../src/backends/browser_jsonp';
import {JSONPBackend, JSONPBackend_, JSONPConnection, JSONPConnection_} from '../../src/backends/jsonp_backend';
import {JSONPBackend, JSONPConnection} from '../../src/backends/jsonp_backend';
import {BaseRequestOptions, RequestOptions} from '../../src/base_request_options';
import {BaseResponseOptions, ResponseOptions} from '../../src/base_response_options';
import {ReadyState, RequestMethod, ResponseType} from '../../src/enums';
@ -48,14 +48,14 @@ class MockBrowserJsonp extends BrowserJsonp {
export function main() {
describe('JSONPBackend', () => {
let backend: JSONPBackend_;
let backend: JSONPBackend;
let sampleRequest: Request;
beforeEach(() => {
const injector = Injector.create([
{provide: ResponseOptions, useClass: BaseResponseOptions, deps: []},
{provide: BrowserJsonp, useClass: MockBrowserJsonp, deps: []},
{provide: JSONPBackend, useClass: JSONPBackend_, deps: [BrowserJsonp, ResponseOptions]}
{provide: JSONPBackend, useClass: JSONPBackend, deps: [BrowserJsonp, ResponseOptions]}
]);
backend = injector.get(JSONPBackend);
const base = new BaseRequestOptions();
@ -75,7 +75,7 @@ export function main() {
describe('JSONPConnection', () => {
it('should use the injected BaseResponseOptions to create the response',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const connection = new JSONPConnection_(
const connection = new JSONPConnection(
sampleRequest, new MockBrowserJsonp(),
new ResponseOptions({type: ResponseType.Error}));
connection.response.subscribe(res => {
@ -88,7 +88,7 @@ export function main() {
it('should ignore load/callback when disposed',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
const connection = new JSONPConnection(sampleRequest, new MockBrowserJsonp());
const spy = new SpyObject();
const loadSpy = spy.spy('load');
const errorSpy = spy.spy('error');
@ -111,7 +111,7 @@ export function main() {
it('should report error if loaded without invoking callback',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
const connection = new JSONPConnection(sampleRequest, new MockBrowserJsonp());
connection.response.subscribe(
res => {
expect('response listener called').toBe(false);
@ -127,7 +127,7 @@ export function main() {
it('should report error if script contains error',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
const connection = new JSONPConnection(sampleRequest, new MockBrowserJsonp());
connection.response.subscribe(
res => {
@ -149,14 +149,14 @@ export function main() {
const base = new BaseRequestOptions();
const req = new Request(base.merge(
new RequestOptions({url: 'https://google.com', method: method})) as any);
expect(() => new JSONPConnection_(req, new MockBrowserJsonp()).response.subscribe())
expect(() => new JSONPConnection(req, new MockBrowserJsonp()).response.subscribe())
.toThrowError();
});
});
it('should respond with data passed to callback',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
const connection = new JSONPConnection(sampleRequest, new MockBrowserJsonp());
connection.response.subscribe(res => {
expect(res.json()).toEqual(({fake_payload: true, blob_id: 12345}));

View File

@ -42,7 +42,7 @@ export function main() {
http = injector.get(Http);
jsonp = injector.get(Jsonp);
jsonpBackend = injector.get(JSONPBackend) as MockBackend;
jsonpBackend = injector.get(JSONPBackend) as any as MockBackend;
xhrBackend = injector.get(XHRBackend) as any as MockBackend;
let xhrCreatedConnections = 0;

View File

@ -7,11 +7,11 @@
*/
import {Injector, ɵglobal as global} from '@angular/core';
import {ApplicationRef, ApplicationRef_} from '@angular/core/src/application_ref';
import {ApplicationRef} from '@angular/core/src/application_ref';
import {SpyObject} from '@angular/core/testing/src/testing_internal';
export class SpyApplicationRef extends SpyObject {
constructor() { super(ApplicationRef_); }
constructor() { super(ApplicationRef); }
}
export class SpyComponentRef extends SpyObject {

View File

@ -10,24 +10,16 @@ import {EventEmitter, Injectable, Type, ɵstringify as stringify} from '@angular
import {MessageBus} from './message_bus';
import {Serializer, SerializerTypes} from './serializer';
/**
* @experimental WebWorker support in Angular is experimental.
*/
export abstract class ClientMessageBrokerFactory {
/**
* Initializes the given channel and attaches a new {@link ClientMessageBroker} to it.
*/
abstract createMessageBroker(channel: string, runInZone?: boolean): ClientMessageBroker;
}
@Injectable()
export class ClientMessageBrokerFactory_ extends ClientMessageBrokerFactory {
export class ClientMessageBrokerFactory {
/** @internal */
_serializer: Serializer;
/** @internal */
constructor(private _messageBus: MessageBus, _serializer: Serializer) {
super();
this._serializer = _serializer;
}
@ -36,31 +28,26 @@ export class ClientMessageBrokerFactory_ extends ClientMessageBrokerFactory {
*/
createMessageBroker(channel: string, runInZone: boolean = true): ClientMessageBroker {
this._messageBus.initChannel(channel, runInZone);
return new ClientMessageBroker_(this._messageBus, this._serializer, channel);
return new ClientMessageBroker(this._messageBus, this._serializer, channel);
}
}
/**
* @experimental WebWorker support in Angular is experimental.
*/
export abstract class ClientMessageBroker {
abstract runOnService(args: UiArguments, returnType: Type<any>|SerializerTypes|null):
Promise<any>|null;
}
interface PromiseCompleter {
resolve: (result: any) => void;
reject: (err: any) => void;
}
export class ClientMessageBroker_ extends ClientMessageBroker {
/**
* @experimental WebWorker support in Angular is experimental.
*/
export class ClientMessageBroker {
private _pending = new Map<string, PromiseCompleter>();
private _sink: EventEmitter<any>;
/** @internal */
public _serializer: Serializer;
constructor(messageBus: MessageBus, _serializer: Serializer, public channel: any) {
super();
/** @internal */
constructor(messageBus: MessageBus, _serializer: Serializer, private channel: any) {
this._sink = messageBus.to(channel);
this._serializer = _serializer;
const source = messageBus.from(channel);
@ -79,7 +66,7 @@ export class ClientMessageBroker_ extends ClientMessageBroker {
return id;
}
runOnService(args: UiArguments, returnType: Type<any>|SerializerTypes): Promise<any>|null {
runOnService(args: UiArguments, returnType: Type<any>|SerializerTypes|null): Promise<any>|null {
const fnArgs: any[] = [];
if (args.args) {
args.args.forEach(argument => {

View File

@ -14,26 +14,22 @@ import {Serializer, SerializerTypes} from '../shared/serializer';
/**
* @experimental WebWorker support in Angular is currently experimental.
*/
export abstract class ServiceMessageBrokerFactory {
/**
* Initializes the given channel and attaches a new {@link ServiceMessageBroker} to it.
*/
abstract createMessageBroker(channel: string, runInZone?: boolean): ServiceMessageBroker;
}
@Injectable()
export class ServiceMessageBrokerFactory_ extends ServiceMessageBrokerFactory {
export class ServiceMessageBrokerFactory {
/** @internal */
_serializer: Serializer;
/** @internal */
constructor(private _messageBus: MessageBus, _serializer: Serializer) {
super();
this._serializer = _serializer;
}
/**
* Initializes the given channel and attaches a new {@link ServiceMessageBroker} to it.
*/
createMessageBroker(channel: string, runInZone: boolean = true): ServiceMessageBroker {
this._messageBus.initChannel(channel, runInZone);
return new ServiceMessageBroker_(this._messageBus, this._serializer, channel);
return new ServiceMessageBroker(this._messageBus, this._serializer, channel);
}
}
@ -45,25 +41,19 @@ export class ServiceMessageBrokerFactory_ extends ServiceMessageBrokerFactory {
*
* @experimental WebWorker support in Angular is currently experimental.
*/
export abstract class ServiceMessageBroker {
abstract registerMethod(
methodName: string, signature: Array<Type<any>|SerializerTypes>|null, method: Function,
returnType?: Type<any>|SerializerTypes): void;
}
export class ServiceMessageBroker_ extends ServiceMessageBroker {
export class ServiceMessageBroker {
private _sink: EventEmitter<any>;
private _methods = new Map<string, Function>();
constructor(messageBus: MessageBus, private _serializer: Serializer, public channel: string) {
super();
/** @internal */
constructor(messageBus: MessageBus, private _serializer: Serializer, private channel: string) {
this._sink = messageBus.to(channel);
const source = messageBus.from(channel);
source.subscribe({next: (message: any) => this._handleMessage(message)});
}
registerMethod(
methodName: string, signature: Array<Type<any>|SerializerTypes>,
methodName: string, signature: Array<Type<any>|SerializerTypes>|null,
method: (..._: any[]) => Promise<any>| void, returnType?: Type<any>|SerializerTypes): void {
this._methods.set(methodName, (message: ReceivedMessage) => {
const serializedArgs = message.args;
@ -71,7 +61,7 @@ export class ServiceMessageBroker_ extends ServiceMessageBroker {
const deserializedArgs = new Array(numArgs);
for (let i = 0; i < numArgs; i++) {
const serializedArg = serializedArgs[i];
deserializedArgs[i] = this._serializer.deserialize(serializedArg, signature[i]);
deserializedArgs[i] = this._serializer.deserialize(serializedArg, signature ![i]);
}
const promise = method(...deserializedArgs);

View File

@ -11,12 +11,12 @@ import {APP_INITIALIZER, ApplicationModule, ErrorHandler, NgModule, NgZone, PLAT
import {DOCUMENT, ɵBROWSER_SANITIZATION_PROVIDERS as BROWSER_SANITIZATION_PROVIDERS} from '@angular/platform-browser';
import {ON_WEB_WORKER} from './web_workers/shared/api';
import {ClientMessageBrokerFactory, ClientMessageBrokerFactory_} from './web_workers/shared/client_message_broker';
import {ClientMessageBrokerFactory} from './web_workers/shared/client_message_broker';
import {MessageBus} from './web_workers/shared/message_bus';
import {PostMessageBus, PostMessageBusSink, PostMessageBusSource} from './web_workers/shared/post_message_bus';
import {RenderStore} from './web_workers/shared/render_store';
import {Serializer} from './web_workers/shared/serializer';
import {ServiceMessageBrokerFactory, ServiceMessageBrokerFactory_} from './web_workers/shared/service_message_broker';
import {ServiceMessageBrokerFactory} from './web_workers/shared/service_message_broker';
import {WebWorkerRendererFactory2} from './web_workers/worker/renderer';
import {WorkerDomAdapter} from './web_workers/worker/worker_adapter';
@ -62,8 +62,8 @@ export function setupWebWorker(): void {
BROWSER_SANITIZATION_PROVIDERS,
Serializer,
{provide: DOCUMENT, useValue: null},
{provide: ClientMessageBrokerFactory, useClass: ClientMessageBrokerFactory_},
{provide: ServiceMessageBrokerFactory, useClass: ServiceMessageBrokerFactory_},
ClientMessageBrokerFactory,
ServiceMessageBrokerFactory,
WebWorkerRendererFactory2,
{provide: RendererFactory2, useExisting: WebWorkerRendererFactory2},
{provide: ON_WEB_WORKER, useValue: true},

View File

@ -11,12 +11,12 @@ import {ErrorHandler, Injectable, InjectionToken, Injector, NgZone, PLATFORM_ID,
import {DOCUMENT, EVENT_MANAGER_PLUGINS, EventManager, HAMMER_GESTURE_CONFIG, HammerGestureConfig, ɵBROWSER_SANITIZATION_PROVIDERS as BROWSER_SANITIZATION_PROVIDERS, ɵBrowserDomAdapter as BrowserDomAdapter, ɵBrowserGetTestability as BrowserGetTestability, ɵDomEventsPlugin as DomEventsPlugin, ɵDomRendererFactory2 as DomRendererFactory2, ɵDomSharedStylesHost as DomSharedStylesHost, ɵHammerGesturesPlugin as HammerGesturesPlugin, ɵKeyEventsPlugin as KeyEventsPlugin, ɵSharedStylesHost as SharedStylesHost, ɵgetDOM as getDOM} from '@angular/platform-browser';
import {ON_WEB_WORKER} from './web_workers/shared/api';
import {ClientMessageBrokerFactory, ClientMessageBrokerFactory_} from './web_workers/shared/client_message_broker';
import {ClientMessageBrokerFactory} from './web_workers/shared/client_message_broker';
import {MessageBus} from './web_workers/shared/message_bus';
import {PostMessageBus, PostMessageBusSink, PostMessageBusSource} from './web_workers/shared/post_message_bus';
import {RenderStore} from './web_workers/shared/render_store';
import {Serializer} from './web_workers/shared/serializer';
import {ServiceMessageBrokerFactory, ServiceMessageBrokerFactory_} from './web_workers/shared/service_message_broker';
import {ServiceMessageBrokerFactory} from './web_workers/shared/service_message_broker';
import {MessageBasedRenderer2} from './web_workers/ui/renderer';
@ -85,12 +85,12 @@ export const _WORKER_UI_PLATFORM_PROVIDERS: StaticProvider[] = [
{provide: SharedStylesHost, useExisting: DomSharedStylesHost},
{
provide: ServiceMessageBrokerFactory,
useClass: ServiceMessageBrokerFactory_,
useClass: ServiceMessageBrokerFactory,
deps: [MessageBus, Serializer]
},
{
provide: ClientMessageBrokerFactory,
useClass: ClientMessageBrokerFactory_,
useClass: ClientMessageBrokerFactory,
deps: [MessageBus, Serializer]
},
{provide: Serializer, deps: [RenderStore]},

View File

@ -10,7 +10,7 @@ import {beforeEach, beforeEachProviders, describe, expect, inject, it} from '@an
import {ON_WEB_WORKER} from '@angular/platform-webworker/src/web_workers/shared/api';
import {RenderStore} from '@angular/platform-webworker/src/web_workers/shared/render_store';
import {Serializer, SerializerTypes} from '@angular/platform-webworker/src/web_workers/shared/serializer';
import {ServiceMessageBroker_} from '@angular/platform-webworker/src/web_workers/shared/service_message_broker';
import {ServiceMessageBroker} from '@angular/platform-webworker/src/web_workers/shared/service_message_broker';
import {createPairedMessageBuses} from './web_worker_test_util';
@ -34,7 +34,7 @@ export function main() {
});
it('should call registered method with correct arguments',
inject([Serializer], (serializer: Serializer) => {
const broker = new ServiceMessageBroker_(messageBuses.ui, serializer, CHANNEL);
const broker = new ServiceMessageBroker(messageBuses.ui, serializer, CHANNEL);
broker.registerMethod(
TEST_METHOD, [SerializerTypes.PRIMITIVE, SerializerTypes.PRIMITIVE], (arg1, arg2) => {
expect(arg1).toEqual(PASSED_ARG_1);
@ -47,7 +47,7 @@ export function main() {
}));
it('should return promises to the worker', inject([Serializer], (serializer: Serializer) => {
const broker = new ServiceMessageBroker_(messageBuses.ui, serializer, CHANNEL);
const broker = new ServiceMessageBroker(messageBuses.ui, serializer, CHANNEL);
broker.registerMethod(TEST_METHOD, [SerializerTypes.PRIMITIVE], (arg1) => {
expect(arg1).toEqual(PASSED_ARG_1);
return new Promise((res, rej) => {

View File

@ -8,7 +8,7 @@
import {Type} from '@angular/core';
import {NgZone} from '@angular/core/src/zone/ng_zone';
import {ClientMessageBroker, ClientMessageBrokerFactory_, UiArguments} from '@angular/platform-webworker/src/web_workers/shared/client_message_broker';
import {ClientMessageBroker, ClientMessageBrokerFactory, UiArguments} from '@angular/platform-webworker/src/web_workers/shared/client_message_broker';
import {MessageBus, MessageBusSink, MessageBusSource} from '@angular/platform-webworker/src/web_workers/shared/message_bus';
import {SpyMessageBroker} from '../worker/spies';
@ -130,7 +130,7 @@ export class MockMessageBus extends MessageBus {
attachToZone(zone: NgZone) {}
}
export class MockMessageBrokerFactory extends ClientMessageBrokerFactory_ {
export class MockMessageBrokerFactory extends ClientMessageBrokerFactory {
constructor(private _messageBroker: ClientMessageBroker) { super(null !, null !); }
createMessageBroker(channel: string, runInZone = true) { return this._messageBroker; }
}

View File

@ -15,10 +15,10 @@ import {BrowserTestingModule} from '@angular/platform-browser/testing';
import {dispatchEvent} from '@angular/platform-browser/testing/src/browser_util';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {ClientMessageBrokerFactory, ClientMessageBrokerFactory_} from '../../../src/web_workers/shared/client_message_broker';
import {ClientMessageBrokerFactory} from '../../../src/web_workers/shared/client_message_broker';
import {RenderStore} from '../../../src/web_workers/shared/render_store';
import {Serializer} from '../../../src/web_workers/shared/serializer';
import {ServiceMessageBrokerFactory_} from '../../../src/web_workers/shared/service_message_broker';
import {ServiceMessageBrokerFactory} from '../../../src/web_workers/shared/service_message_broker';
import {MessageBasedRenderer2} from '../../../src/web_workers/ui/renderer';
import {WebWorkerRendererFactory2} from '../../../src/web_workers/worker/renderer';
import {PairedMessageBuses, createPairedMessageBuses} from '../shared/web_worker_test_util';
@ -180,10 +180,10 @@ function createWebWorkerBrokerFactory(
const wwMessageBus = messageBuses.worker;
// set up the worker side
const wwBrokerFactory = new ClientMessageBrokerFactory_(wwMessageBus, wwSerializer);
const wwBrokerFactory = new ClientMessageBrokerFactory(wwMessageBus, wwSerializer);
// set up the ui side
const uiBrokerFactory = new ServiceMessageBrokerFactory_(uiMessageBus, uiSerializer);
const uiBrokerFactory = new ServiceMessageBrokerFactory(uiMessageBus, uiSerializer);
const renderer = new MessageBasedRenderer2(
uiBrokerFactory, uiMessageBus, uiSerializer, uiRenderStore, domRendererFactory);
renderer.start();

View File

@ -125,15 +125,15 @@ export declare class ApplicationModule {
}
/** @stable */
export declare abstract class ApplicationRef {
readonly abstract componentTypes: Type<any>[];
readonly abstract components: ComponentRef<any>[];
readonly abstract isStable: Observable<boolean>;
readonly abstract viewCount: number;
abstract attachView(view: ViewRef): void;
abstract bootstrap<C>(componentFactory: ComponentFactory<C> | Type<C>, rootSelectorOrNode?: string | any): ComponentRef<C>;
abstract detachView(view: ViewRef): void;
abstract tick(): void;
export declare class ApplicationRef {
readonly componentTypes: Type<any>[];
readonly components: ComponentRef<any>[];
readonly isStable: Observable<boolean>;
readonly viewCount: number;
attachView(viewRef: ViewRef): void;
bootstrap<C>(componentOrFactory: ComponentFactory<C> | Type<C>, rootSelectorOrNode?: string | any): ComponentRef<C>;
detachView(viewRef: ViewRef): void;
tick(): void;
}
/** @experimental */
@ -695,13 +695,13 @@ export declare const PLATFORM_INITIALIZER: InjectionToken<(() => void)[]>;
export declare const platformCore: (extraProviders?: StaticProvider[] | undefined) => PlatformRef;
/** @stable */
export declare abstract class PlatformRef {
readonly abstract destroyed: boolean;
readonly abstract injector: Injector;
/** @stable */ abstract bootstrapModule<M>(moduleType: Type<M>, compilerOptions?: CompilerOptions | CompilerOptions[]): Promise<NgModuleRef<M>>;
/** @experimental */ abstract bootstrapModuleFactory<M>(moduleFactory: NgModuleFactory<M>): Promise<NgModuleRef<M>>;
abstract destroy(): void;
abstract onDestroy(callback: () => void): void;
export declare class PlatformRef {
readonly destroyed: boolean;
readonly injector: Injector;
/** @stable */ bootstrapModule<M>(moduleType: Type<M>, compilerOptions?: CompilerOptions | CompilerOptions[]): Promise<NgModuleRef<M>>;
/** @experimental */ bootstrapModuleFactory<M>(moduleFactory: NgModuleFactory<M>): Promise<NgModuleRef<M>>;
destroy(): void;
onDestroy(callback: () => void): void;
}
/** @experimental */

View File

@ -79,15 +79,16 @@ export declare class Jsonp extends Http {
}
/** @deprecated */
export declare abstract class JSONPBackend extends ConnectionBackend {
export declare class JSONPBackend extends ConnectionBackend {
createConnection(request: Request): JSONPConnection;
}
/** @deprecated */
export declare abstract class JSONPConnection implements Connection {
export declare class JSONPConnection implements Connection {
readyState: ReadyState;
request: Request;
response: Observable<Response>;
abstract finished(data?: any): void;
finished(data?: any): void;
}
/** @deprecated */

View File

@ -2,13 +2,13 @@
export declare function bootstrapWorkerUi(workerScriptUri: string, customProviders?: StaticProvider[]): Promise<PlatformRef>;
/** @experimental */
export declare abstract class ClientMessageBroker {
abstract runOnService(args: UiArguments, returnType: Type<any> | SerializerTypes | null): Promise<any> | null;
export declare class ClientMessageBroker {
runOnService(args: UiArguments, returnType: Type<any> | SerializerTypes | null): Promise<any> | null;
}
/** @experimental */
export declare abstract class ClientMessageBrokerFactory {
abstract createMessageBroker(channel: string, runInZone?: boolean): ClientMessageBroker;
export declare class ClientMessageBrokerFactory {
createMessageBroker(channel: string, runInZone?: boolean): ClientMessageBroker;
}
/** @experimental */
@ -62,13 +62,13 @@ export declare const enum SerializerTypes {
}
/** @experimental */
export declare abstract class ServiceMessageBroker {
abstract registerMethod(methodName: string, signature: Array<Type<any> | SerializerTypes> | null, method: Function, returnType?: Type<any> | SerializerTypes): void;
export declare class ServiceMessageBroker {
registerMethod(methodName: string, signature: Array<Type<any> | SerializerTypes> | null, method: (..._: any[]) => Promise<any> | void, returnType?: Type<any> | SerializerTypes): void;
}
/** @experimental */
export declare abstract class ServiceMessageBrokerFactory {
abstract createMessageBroker(channel: string, runInZone?: boolean): ServiceMessageBroker;
export declare class ServiceMessageBrokerFactory {
createMessageBroker(channel: string, runInZone?: boolean): ServiceMessageBroker;
}
/** @experimental */