2

我正在为跨多个应用程序共享的组件创建一个角度库。在库中的组件内使用库内部的服务时,我遇到了麻烦。

该服务旨在注入应用程序的根目录(而不是库),并且可以在整个应用程序中使用。

在这种情况下,我们正在查看ToastServiceand UIToastComponent。是UIToastComponentUIToastModule.

然后应用程序导入UIToastModule应用程序内部的AppModule,其中还提供ToastService.

<ui-toast></ui-toast>标签位于应用程序的app.component.html文件中。

这个想法是,在应用程序内部的任何组件中,开发人员都可以注入ToastService和调用this.toastService.success('Great Success!'),由 接收UIToastComponent并显示 toast。

似乎无法获取服务,并且在运行时出现以下constructor错误:UIToastComponent

Uncaught ReferenceError: ToastService is not defined
at UIToastComponent.ctorParameters (ngx-example-library.js:197)
at ReflectionCapabilities._ownParameters (core.js:2060)
at ReflectionCapabilities.parameters (core.js:2095)
at JitReflector.parameters (platform-browser-dynamic.js:61)
at CompileMetadataResolver._getDependenciesMetadata (compiler.js:15635)
at CompileMetadataResolver._getTypeMetadata (compiler.js:15527)
at CompileMetadataResolver.getNonNormalizedDirectiveMetadata 
(compiler.js:15012)
at CompileMetadataResolver.loadDirectiveMetadata (compiler.js:14866)
at eval (compiler.js:34392)
at Array.forEach (<anonymous>)

ToastService内部的导入语句UIToastComponent如下所示:

import { ToastService } from '../../services/toast.service';

该库遵循Angular Package Format v5,最初基于https://github.com/juristr/ngx-tabs-libdemo

这是该库的源代码: ngx-example-library

编辑

我已经forRoot()按照 Günter Zöchbauer 的建议实施了,但不幸的是我仍然得到相同的结果,很可能我实施不正确......

以下是库中新创建的UICoreModule外观:

import { ModuleWithProviders, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { UIToastComponent } from './components/toast/toast.component';
import { ToastService } from './services/toast.service';

@NgModule({
    declarations: [
        UIToastComponent,
    ],
    providers: [],
    imports: [
        CommonModule,
    ],
    exports: [
        UIToastComponent,
    ]
})

export class UICoreModule {

    public static forRoot(): ModuleWithProviders {
        return {ngModule: UICoreModule, providers: [ToastService]};
    }

}

AppModule是应用程序的内部:

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

import {AppComponent} from './app.component';
import {UICoreModule} from 'ngx-example-library';

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        UICoreModule.forRoot()
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {
}

感谢对此的帮助,这真是令人难以置信。打赌这真的很容易——当你知道怎么做的时候!

编辑 (2)

上面提到的解决方案在 AOT 模式下工作,但不是JIT 模式。很高兴现在能忍受这一点,无论如何,该应用程序都会构建 AOT。开发可能会随着应用程序的增长而变化。

4

1 回答 1

2

您需要在定义您的包的模块中实现,在那里提供forRoot服务并导入模块AppModuleMyModule.forRoot()

另请参阅https://angular.io/guide/ngmodule-faq#what-is-the-forroot-method

于 2018-01-15T17:17:12.760 回答