【发布时间】:2019-09-11 17:57:39
【问题描述】:
我已经创建了一个主题库,我在其中根据所选主题更改样式表路径。我的问题是我的库中的路径是assets/themes,但是如果我将库添加到项目中,那将不再工作,因为它指向项目的assets/themes 而不是库的。有没有办法在库中相对引用该路径?
【问题讨论】:
我已经创建了一个主题库,我在其中根据所选主题更改样式表路径。我的问题是我的库中的路径是assets/themes,但是如果我将库添加到项目中,那将不再工作,因为它指向项目的assets/themes 而不是库的。有没有办法在库中相对引用该路径?
【问题讨论】:
您可以将相对路径保留在 environment.ts 中,然后使用 forRoot 将其传递给库模块。
假设您想根据您的要求使用libService 或任何其他文件中的路径,
试试这样:
app.module.ts
import { NgModule } from '@angular/core';
import { LibModule } from 'some-library';
@NgModule({
imports: [
libModule.forRoot({
environment: environment
})
]
})
LibModule.module.ts
export class LibModule{
static forRoot(config): ModuleWithProviders {
return {
ngModule: LibModule,
providers: [LibService, {provide: CONFIG, useValue: config}]
};
}
}
libService.service:
export const CONFIG = new InjectionToken<any>('config');
export class LibService{
constructor(@Inject(CONFIG) private config:any) {
console.log(config)
}
}
【讨论】:
{provide: config, useValue: config} 吗?确保它是 config 而不是 CONFIG,我在几分钟前编辑了答案
InjectionToken 我正在使用它。 export const PATH_CONFIG = new InjectionToken<string>('assets.path'); 并像 {provide: PATH_CONFIG, useValue:config} 一样使用它
@Inject('PATH_CONFIG') private config:string,它就不会再抛出错误了。
libService:export const CONFIG = new InjectionToken<any>('config'); export class LibService{ constructor(@Inject(CONFIG) private config:any) { console.log(config) } }
libModule:将提供者更改为[LibService, {provide: CONFIG, useValue: config}]