2

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?

rjdkolb
  • 10,377
  • 11
  • 69
  • 89
Mark Sandman
  • 3,293
  • 12
  • 40
  • 60
  • This might clear your doubts: https://stackoverflow.com/questions/41289264/what-is-in-angular-2-opaque-token-and-whats-the-point – Peter Sep 12 '17 at 10:56

0 Answers0