【发布时间】:2019-12-09 21:58:00
【问题描述】:
我正在开发一个自定义 Angular 组件库,当添加到其他 Angular 项目时,它需要配置一些参数。这个库在添加到其他Angular项目时需要配置一些参数。
我研究了在 Angular 服务中注入数据的方法,以下是对已完成工作的概述:
app.component.html(来自我们将添加此自定义库的其他 Angular 项目)
<my-component paramA="abc" paramB="def"></my-component>
我的组件.component.ts
@Component({
...
providers: [
{ provide: 'paramA', useValue: this.paramA },
{ provide: 'paramB', useValue: this.paramB },
]
}
export class MyComponent implements OnInit {
@Input() paramA: string;
@Input() paramB: string;
constructor(private serviceA: AService, private serviceB: BService);
...
}
a.service.ts
@Injectable({
providedIn: 'root'
})
export class AService {
constructor(
@Inject('paramA') public paramA: string
) {
this.paramA = paramA;
}
}
这会引发错误,因为组件装饰器无法访问类属性。
实现这一目标的正确方法是什么?
【问题讨论】:
标签: angular typescript dependency-injection web-component angular-library