【发布时间】:2020-07-04 05:20:32
【问题描述】:
我正在尝试创建一个包含服务和组件的自定义库。但是,当我这样做时,我得到了常见的“不是已知元素”错误。
即使我做了一个非常简单的示例,也会发生这种情况。重现步骤:
ng new example --create-application=falsecd example && ng g library example-libng g application example-appng build example-lib- 将 example-lib 项目中的模块导入 example-app:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ExampleLibModule } from 'example-lib';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ExampleLibModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
- 将组件添加到example-app中的app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<lib-example-lib></lib-example-lib>`,
// templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'example-app';
}
如果我按照上述步骤操作,我会收到描述的错误。这似乎只是组件的问题,因为如果我在 example-lib 中向服务添加虚拟方法:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ExampleLibService {
constructor() { }
hello() {
return 'hello';
}
}
然后将该服务导入到我的示例应用组件中:
import { Component } from '@angular/core';
import { ExampleLibService } from 'example-lib';
@Component({
selector: 'app-root',
// template: `<lib-example-lib></lib-example-lib>`,
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'example-app';
constructor(private exampleService: ExampleLibService) {
this.title = this.exampleService.hello();
}
}
这样做,一切正常,我可以正常访问我的服务。因此,这似乎只是组件的问题,但一切都具有来自角度 cli 的开箱即用配置。任何指导将不胜感激!
我的系统:
Angular CLI: 9.1.8
Node: 12.15.0
OS: darwin x64
【问题讨论】:
-
您是否已将其添加到
ExampleLibModule的 providers 数组中/您能否向我们展示示例库模块? -
你导出了示例库组件吗?
标签: angular typescript