我在构造函数中有一个带有参数的服务,这里是一个简单的字符串,稍后在 url 或其他对象上。该参数是为服务的内部行为设置的,这里只是实例化不同的值。
constructor(@Inject(AUTHOR_TYPE) public authType: string ) {
console.log('Auth type is ' + authType);
if(authType == 'international')
this.authors = ["a1","a2","a2","a3"];
else
this.authors = ["local1","local2","local2","local3"];
}
该服务在组件内部使用。这个组件有一个输入参数,使组件灵活和可重用。
export class AuthorsComponent implements OnInit {
@Input('type')
type: 'local' | 'international' = "local";
authors: string[];
constructor(service: AuthorsService) {
this.authors = service.getAuthors();
}
ngOnInit(): void {
console.log('component init as ' + this.type);
}
}
我希望有一个组件能够使用输入参数(或其他绑定模式)在不同类型之间切换,并且基于组件类型能够设置内部服务以更改行为。
在下面的实时示例中,我只有一个带有自定义参数的组件作者,并且在服务内部检索作者列表,有没有办法实现这一点?
[更新]
在服务上使用 @Inject 并实际使用 2 个组件和 2 个预定义的 InjectionTocken 的可能解决方案。似乎仍然不是最佳解决方案,因为我有一个通用组件或多或少是空的,只是摸索并显示子组件+ 2个指定组件。达到了范围,但我生成了太多组件。仍然对其他解决方案持开放态度。谢谢