簡體   English   中英

在 Angular 中,您可以在不從擴展組件傳遞的情況下注入超級 class 嗎?

[英]In Angular, can you inject into a super class without passing it from extended components?

我正在嘗試在我的超級 class 上獲取 PLATFORM_ID,但我寧願不必從擴展它的所有類中傳遞它。 我嘗試將其設為可選,但它只是以未定義的形式返回。

這是我的基地 class

 constructor(
    public bucketType: 'quote' | 'list' | 'quote_cart' | 'cart',
    public http: HttpClient,
    public gaService: GaService,
    public gtmService: GtmDataLayerService,
    @Inject(PLATFORM_ID) private platformId?: string
) {

您的服務可能如下所示:

一些.service.ts

let platform: string;

export function setPlatform(value) {
  platform = value;
}

@Injectable(...)
export class SomeService {

  constructor() {
    console.log(platform);
  }
}

現在您需要做的就是只設置一次平台變量:

app.module.ts

import { setPlatform } from './some.service';

@NgModule(...)
export class AppModule {
  constructor(@Inject(PLATFORM_ID) private platformId?: string) {
    setPlatform(platformId);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM