Skip to content

Commit

Permalink
feat(core): improve WindowService to work on both browser and server
Browse files Browse the repository at this point in the history
  • Loading branch information
tinesoft committed Jul 18, 2021
1 parent 7233aa0 commit cdb5e0a
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 20 deletions.
18 changes: 5 additions & 13 deletions libs/ngx-cookieconsent/src/lib/service/window.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
/* tslint:disable:no-unused-variable */

import { TestBed, async, inject } from '@angular/core/testing';
import { DOCUMENT } from '@angular/common';
import { TestBed, inject } from '@angular/core/testing';
import { WindowService } from './window.service';

declare const document: Document

describe('Service: Window, Angular Tests', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [WindowService]
providers: [{ provide: DOCUMENT, useValue: document}, WindowService]
});
});

Expand All @@ -17,14 +20,3 @@ describe('Service: Window, Angular Tests', () => {
}));
});

describe('Service: Window, Isolated Tests', () => {

let service: WindowService;

beforeEach(() => { service = new WindowService(); });

it('nativeWindow should be defined and equaled to "window" object', () => {
expect(service.nativeWindow).toBeDefined();
expect(service.nativeWindow).toBe(window);
});
});
13 changes: 6 additions & 7 deletions libs/ngx-cookieconsent/src/lib/service/window.service.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import { Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { Inject, Injectable } from '@angular/core';

/**
* Service to interact with the window object.
* Service to interact with the `window` object (or its equivalent on a server platform).
*/
@Injectable()
export class WindowService {

constructor(@Inject(DOCUMENT) private _doc: Document) {}

get nativeWindow(): any {
return _window();
return this._doc?.defaultView || window;
}
}

function _window(): any {
// Return the global native browser window object
return typeof window !== 'undefined' ? window : undefined;
}

0 comments on commit cdb5e0a

Please sign in to comment.