Angular 核心提供商喜欢 PLATFORM_ID
Angular core providers like PLATFORM_ID
在基于价值的提供者(代币)中,我们有这样的东西(在模块中):
const CONFIG = 'CONFIG';
providers: [
{
provide: CONFIG,
useValue: myConfigObj,
},
因为我们在模块中定义了提供者,所以在服务中我们可以这样做:
constructor(@Optional() @Inject(CONFIG) config) {
console.log(config);
}
但是当我们想像这样访问PLATFORM_ID
时:
constructor(@Inject(PLATFORM_ID) private platformId) {
我们没有在模块的提供程序中定义 PLATFORM_ID
。这是在哪个模块中定义的? useValue
是什么?
已经在 Angular Community Discord 服务器上为您解答了这个问题,但我不确定您是否看到了。
通过在 main.ts 中调用 platformBrowserDynamic()
(如果是 @Angular/universal 应用程序,则调用 platformDynamicServer()
),创建一个由 [=12= 配置的注入器]. PLATFORM_ID
此处提供。
该值是一个字符串:'browser'
(或 'server'
对于通用应用程序)。
您可以在此处阅读有关平台注入器(它是根注入器的父级)的更多信息:https://angular.io/guide/hierarchical-dependency-injection#platform-injector
编辑:应要求,源代码链接:此处提供: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
在基于价值的提供者(代币)中,我们有这样的东西(在模块中):
const CONFIG = 'CONFIG';
providers: [
{
provide: CONFIG,
useValue: myConfigObj,
},
因为我们在模块中定义了提供者,所以在服务中我们可以这样做:
constructor(@Optional() @Inject(CONFIG) config) {
console.log(config);
}
但是当我们想像这样访问PLATFORM_ID
时:
constructor(@Inject(PLATFORM_ID) private platformId) {
我们没有在模块的提供程序中定义 PLATFORM_ID
。这是在哪个模块中定义的? useValue
是什么?
已经在 Angular Community Discord 服务器上为您解答了这个问题,但我不确定您是否看到了。
通过在 main.ts 中调用 platformBrowserDynamic()
(如果是 @Angular/universal 应用程序,则调用 platformDynamicServer()
),创建一个由 [=12= 配置的注入器]. PLATFORM_ID
此处提供。
该值是一个字符串:'browser'
(或 'server'
对于通用应用程序)。
您可以在此处阅读有关平台注入器(它是根注入器的父级)的更多信息:https://angular.io/guide/hierarchical-dependency-injection#platform-injector
编辑:应要求,源代码链接:此处提供: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