【问题标题】:How to use relative path to files inside Angular Library?如何使用 Angular 库中文件的相对路径?
【发布时间】:2019-09-11 17:57:39
【问题描述】:

我已经创建了一个主题库,我在其中根据所选主题更改样式表路径。我的问题是我的库中的路径是assets/themes,但是如果我将库添加到项目中,那将不再工作,因为它指向项目的assets/themes 而不是库的。有没有办法在库中相对引用该路径?

【问题讨论】:

    标签: angular angular-library


    【解决方案1】:

    您可以将相对路径保留在 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)
       }
    }
    

    【讨论】:

    • 你在 lib.modue 中添加了{provide: config, useValue: config} 吗?确保它是 config 而不是 CONFIG,我在几分钟前编辑了答案
    • 实际上我已经声明了一个InjectionToken 我正在使用它。 export const PATH_CONFIG = new InjectionToken&lt;string&gt;('assets.path'); 并像 {provide: PATH_CONFIG, useValue:config} 一样使用它
    • 所以,我已经设法查明了问题的一部分。我认为在设置配置之前以某种方式构建了服务。如果我从服务的构造函数中删除@Inject('PATH_CONFIG') private config:string,它就不会再抛出错误了。
    • libServiceexport const CONFIG = new InjectionToken&lt;any&gt;('config'); export class LibService{ constructor(@Inject(CONFIG) private config:any) { console.log(config) } }
    • libModule:将提供者更改为[LibService, {provide: CONFIG, useValue: config}]
    猜你喜欢
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多