Search code examples
angulartypescriptlifecycleangular-servicesstatic-variables

In Angular2+, when are static variables set?


Suppose I have a service in Angular 5 that looks like

@Injectable()
export class CognitoUtil {

    constructor(
        private anotherService: AnotherService
    ) {}

    public static GREETING = "Howdie Partner";

}

What is the lifecycle of the variable GREETING?

When is it set? Is it set as soon as the app is loaded before it is even bootstrapped (it seems so to me) ? Is there anyway to get something to happen before it runs - for example, to set other values that might affect the final given value to GREETING?

I'd really appreciate some clarification on this.

Thanks!


Solution

  • First of all, i think you are right about "When is it set".

    Second, from my perspective, you should not use static variables in the services because you are violating Dependencies Injection pattern.

    If you must use it, i think you can try to use the APP_INITIALIZER provided by Angular.

    as example:

    import { HttpClientModule } from "@angular/common/http";
    
    import { CognitoService } from './cognito.service';
    import { AnotherService } from './another.service';
    
    export function init_app(anotherService : AnotherService ) {
        return () => {
            CognitoService.GREETING = anotherService.someValue;
        };
    }
    
    @NgModule({
      imports: [HttpClientModule],
      providers: [
        AnotherService,
        CognitoService,
        { provide: APP_INITIALIZER, useFactory: init_app, deps: [AnotherService], multi: true }
      ]
    })
    export class AppLoadModule { }