我正在编写一个浏览器扩展程序,它为Firefox和Chrome提供不同的服务。需要根据环境变量注入每个服务的正确版本。虽然我可以在AppModule中正确地注入适当的服务,但我不确定如何在没有hacky解决方法的情况下在我的根组件中获得适当的服务。
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './index';
import { environment } from '../environments/environment';
import { MessageService } from './messaging.service';
import { MessageServiceFirefox } from './ff.messaging.service';
import { ScreenshotService } from './screenshot.service';
import { ScreenshotServiceFirefox } from './ff.screenshot.service';
export function screenshotFactory() {
if (environment.envName == 'prod-ff' || environment.envName == 'ff') {
return new ScreenshotServiceFirefox();
} else {
return new ScreenshotService();
}
}
export function messageFactory() {
if (environment.envName == 'prod-ff' || environment.envName == 'ff') {
return new MessageServiceFirefox();
} else {
return new MessageService();
}
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
],
providers: [
{
provide: ScreenshotService,
useFactory: screenshotFactory
},
{
provide: MessageService,
useFactory: messageFactory
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
import { ScreenshotService } from './screenshot.service';
import { MessageService } from './messaging.service';
// Would need to import ScreenshotServiceFirefox and MessageServiceFirefox
// and have conditional logic to establish correct ScreenshotService and MessageService
@Component({
moduleId: module.id,
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [ScreenshotService, MessageService]
})
export class AppComponent {
constructor(private screenshotService: ScreenshotService, private messageService: MessageService) {}
takeScreenshot (){
this.messageService.injectScript()
.then(this.screenshotService.takeScreenshot)
.then(this.screenshotService.convertToBlob)
.then(this.screenshotService.downloadLocally)
}
}
我还尝试使用解决方案here,here和here,但没有一个处理从根组件中访问注入的服务而不使用相同的条件逻辑。< / p>
我愿意接受其他方法的建议。