angularangular-providers

Angular core providers like PLATFORM_ID


In value-based providers (tokens), we have something like this (in the module):

const CONFIG = 'CONFIG';
providers: [
    {
        provide: CONFIG,
        useValue: myConfigObj,
    },

Because we defined the provider in module, in a service we can do this:

constructor(@Optional() @Inject(CONFIG) config) {
    console.log(config);
}

But when we want to access PLATFORM_ID like this:

constructor(@Inject(PLATFORM_ID) private platformId) {

We don't define PLATFORM_ID in the module's provider. In which module this is defined? And what is the useValue ?


Solution

  • Already answered this for you on the Angular Community Discord server, but I'm not sure you saw that.

    By calling platformBrowserDynamic() (or platformDynamicServer() in case of an @Angular/universal app) in main.ts, an injector is created which is configured by PlatformModule. PLATFORM_ID is provided here.

    The value is a string: 'browser' (or 'server' for a universal app).

    You can read more about the platform injector (which is a parent of the root injector) here: https://angular.io/guide/hierarchical-dependency-injection#platform-injector

    edit: By request, the links to the source code: It's provided here: https://github.com/angular/angular/blob/11.2.9/packages/platform-browser-dynamic/src/platform_providers.ts#L27, then it get's passed into a createPlatformFactory: https://github.com/angular/angular/blob/11.2.9/packages/platform-browser-dynamic/src/platform-browser-dynamic.ts#L29 where the Injector is created with the passed in providers: https://github.com/angular/angular/blob/bafec59b33819b8a47eb9723f8014618c9f1b991/packages/core/src/application_ref.ts#L181-L186