我对 AngularJS 后的 Angular 版本有点陌生,并决定尝试一下。我想做的是构建一个 UI 组件库,以及一个使用该库的应用程序。在我的库中,我决定将组件创建为 WebComponents,因此按照我到目前为止找到的教程,我有类似的东西
import { Injector, NgModule } from '@angular/core'
import { createCustomElement } from '@angular/elements';
import { MyButtonComponent} from './my-button.component'
@NgModule({
declarations: [MyButtonComponent],
entryComponents: [MyButtonComponent]
})
export class MyButtonModule {
constructor(injector: Injector) {
const myButton = createCustomElement(MyButtonComponent, { injector });
customElements.define('my-button', myButton);
}
}
对于我的自定义组件。如果我将组件的所有文件(模块、组件、模板和 SCSS 文件)直接添加到我的应用程序中,它就会按预期工作,所以我知道我的组件声明是正确的。但是,如果在我的应用程序中包含库中的组件,那么当使用 ngserve 运行我的应用程序时,我会看到错误:
Error: StaticInjectorError(AppModule)[MyButtonModule -> Injector]:
StaticInjectorError(Platform: core)[MyButtonModule -> Injector]:
NullInjectorError: No provider for Injector!
我正在使用 Angular 6,两个项目都在本地运行,并且我正在使用 ng-packagr 来捆绑我的库。我在我的库中添加了 @angular/core
和 @angular/elements
作为 peerDependency
,并且在我的主应用程序中我必须添加
"resolutions": {
"@angular/core": "6.1.4"
}
解决错误无法重新声明 block 范围变量'ngDevMode'
(不确定这是否相关)。最初我认为注入(inject)错误可能是由 this 引起的但我已将 preserveSymlinks
添加到我的 angular.json
文件中,但仍然出现错误。
有什么想法可能导致这种情况吗?
更新:如果我从库文件夹中手动复制文件并将它们粘贴到主应用程序的 node_modules
文件夹中,它就会起作用,这让我认为这涉及符号链接(symbolic link)。
最佳答案
要使用npm link
'ed库运行karma,需要在test
中添加preserveLinks: true
(builder-angular:业力
部分)angular.json
:
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"preserveSymlinks": true,
// ...
关于Angular6:使用本地库时没有注入(inject)器的提供程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52017988/