我正在使用该包ngx-cookieconsent
它将模块导入为:
const cookieConfig: NgcCookieConsentConfig = {
"cookie": {
"domain": "localhost"
},
...
"theme": "block",
"content": {
"policy": "Cookie Policy"
}
};
...
@NgModule({
imports: [
NgcCookieConsentModule.forRoot(cookieConfig)
]
但是,配置上的域属性将在运行时设置,因此我不能将其定义为常量。为了解决这个问题,我做了以下工作:
创建了一个ConfigurationService
获取配置并存储它:
@Injectable()
export class ConfigurationService {
private configuration: IServerConfiguration;
constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) { }
loadConfig() {
return this.http.get<IServerConfiguration>(this.baseUrl + 'Configuration')
.pipe(
tap(config => {
this.configuration = <IServerConfiguration>(config);
})
)
.toPromise();
}
public domain(): string {
return this.configuration.domain;
}
}
这被设置为APP_INITIALIZER
这样首先调用配置:
export function loadConfiguration(configService: ConfigurationService) {
return () => configService.loadConfig();
}
...
providers: [
ConfigurationService,
{
provide: APP_INITIALIZER,
useFactory: loadConfiguration,
multi: true,
deps: [ConfigurationService]
}],
然后创建一个类来使用配置创建我的 cookieConsentOptions 对象:
@Injectable()
export class CookieConstentService {
cookieDomain: string;
constructor(configService: ConfigurationService) {
this.cookieDomain = configService.domain();
}
get cookieConstentOptions(): NgcCookieConsentConfig {
return {
"cookie": {
"domain": this.cookieDomain
},
"position": "top-right",
"content": {
"message": "This website uses cookies to ensure you get the best experience on our website."
}
};
}
Issue
我已经在 configService 和 CookieConstentService 之间设置了依赖关系,这样我只有在拥有配置值时才创建 cookie 选项。
但是,我不确定如何将动态值传递给.forRoot()
一个模块的。我应该能够做到cookieConsentService.cookieConstentOptions()
获取该对象,但我不确定在哪里实例化该对象以在模块导入中使用。它需要依赖项,因此不能自己创建一个新实例。
任何想法如何有效地将方法注入到第三方模块中forRoot()
?
Thanks