fix(platform-server): fix an exception when HostListener('window:scroll') is used on the server (#15019)

This commit is contained in:
vikerman 2017-03-14 20:48:01 -07:00 committed by Chuck Jazdzewski
parent c10c060d20
commit 4f7d62adac
2 changed files with 26 additions and 2 deletions

View File

@ -27,11 +27,26 @@ function _notImplemented(methodName: string) {
return new Error('This method is not implemented in Parse5DomAdapter: ' + methodName);
}
function _getElement(el: any, name: string) {
for (let i = 0; i < el.childNodes.length; i++) {
let node = el.childNodes[i];
if (node.name === name) {
return node;
}
}
return null;
}
/**
* Parses a document string to a Document object.
*/
export function parseDocument(html: string) {
return parse5.parse(html, {treeAdapter: parse5.treeAdapters.htmlparser2});
let doc = parse5.parse(html, {treeAdapter: parse5.treeAdapters.htmlparser2});
let docElement = _getElement(doc, 'html');
doc['head'] = _getElement(docElement, 'head');
doc['body'] = _getElement(docElement, 'body');
doc['_window'] = {};
return doc;
}

View File

@ -7,7 +7,7 @@
*/
import {APP_BASE_HREF, PlatformLocation, isPlatformServer} from '@angular/common';
import {ApplicationRef, CompilerFactory, Component, NgModule, NgModuleRef, NgZone, PLATFORM_ID, PlatformRef, destroyPlatform, getPlatform} from '@angular/core';
import {ApplicationRef, CompilerFactory, Component, HostListener, NgModule, NgModuleRef, NgZone, PLATFORM_ID, PlatformRef, destroyPlatform, getPlatform} from '@angular/core';
import {TestBed, async, inject} from '@angular/core/testing';
import {Http, HttpModule, Response, ResponseOptions, XHRBackend} from '@angular/http';
import {MockBackend, MockConnection} from '@angular/http/testing';
@ -57,6 +57,9 @@ class TitleAppModule {
class MyAsyncServerApp {
text = '';
@HostListener('window:scroll')
track() { console.error('scroll'); }
ngOnInit() {
Promise.resolve(null).then(() => setTimeout(() => { this.text = 'Works!'; }, 10));
}
@ -141,7 +144,13 @@ export function main() {
platform.bootstrapModule(ExampleModule).then((moduleRef) => {
expect(isPlatformServer(moduleRef.injector.get(PLATFORM_ID))).toBe(true);
const doc = moduleRef.injector.get(DOCUMENT);
expect(doc.head).toBe(getDOM().querySelector(doc, 'head'));
expect(doc.body).toBe(getDOM().querySelector(doc, 'body'));
expect((<any>doc)._window).toEqual({});
expect(getDOM().getText(doc)).toEqual('Works!');
platform.destroy();
});
}));