Why use a Service and Token / OpaqueToken to get the Window object in Angular

185 views Asked by At

I was speaking to a colleague the other day who didn't like my code. In my Angular Component I access the window object like so private myWindow = window;

He told me a better way was to use a Service and a Token / OpaqueToken (I have no idea what a OpaqueToken is), something like so...

import {
    Injectable,
    OpaqueToken,
} from '@angular/core';

export const WindowToken = new OpaqueToken('app.window');

@Injectable()
export class WindowService {
    getWindow(): Window {
        return window;
    }
}

and then I can inject the service and get the object like so...

myWindow: Window;
constructor(@Inject(WindowToken) windowRef: WindowService) {
        this.myWindow = windowRef.getWindow();
}

It all seems very nice and clean but I don't understand the advantage of using a Token (or what the Token does) and service over just assigning a variable with the window object - can someone tell me why using the service and token is better practice?

0

There are 0 answers