我正在尝试制作一个通用组件来显示列表资源。我遇到了在HTML中实例化组件的问题。我正在使用此answer来尝试解决问题,但我觉得它不起作用。
我有这个组件
<ion-list>
<ion-item-sliding *ngFor="let entity of entityList" #item>
<ion-item (click)="navigateToDetail(entity.id)">
<ion-avatar item-left>
<img src="http://modexenergy.com/wp-content/themes/modex_wp/img/avatar.png">
</ion-avatar>
<h2>{{ entity.email }}</h2>
<ion-icon name="arrow-forward" item-right></ion-icon>
</ion-item>
<ion-item-options side="right">
<button ion-button color="danger" (click)="delete(entity.id)">
<ion-icon name="trash"></ion-icon>Delete
</button>
</ion-item-options>
</ion-item-sliding>
</ion-list>
export class PageListBaseComponent<T extends IHasId> {
@Input() entityType: T;
@Input() detailPageType: any;
public entityList: T[];
constructor(public navCtrl: NavController, public navParams: NavParams, public baseProvider: ProviderBase<T>) {
baseProvider.getList().subscribe(entities => {
this.entityList = entities;
console.log(entities);
});
}
delete(id: number) {
console.log(id);
//this.baseProvider.deleteById(id).subscribe(result => {
// console.log(result);
//});
}
navigateToDetail(id: number) {
console.log('test ' + id)
this.navCtrl.push(this.detailPageType, { id })
}
}
我从用户页面初始化它是这样的:
<ion-content padding>
<page-list-base [entityType]="userType" [detailPageType]="userDetailType">
</page-list-base>
</ion-content>
export class UsersPage {
public userType: User;
public userDetailType: ProfilePage;
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
}
这不起作用,因为我的Component引用构造函数中的public baseProvider: ProviderBase<T>
,Dependency Inject无法解析该类型。
我希望能够尽可能多地重复使用它。如何正确初始化此通用组件?如果那是不可能的,我怎么能在T结算后迟到了baseProvider?
答案 0 :(得分:2)
我通过延迟初始化并使依赖为@Input
属性
export class PageListBaseComponent<T extends IHasId> {
@Input() detailPageType: any;
@Input() set baseProvider(provider: ProviderBase<T>) {
provider.getList().subscribe(entities => {
this.entityList = entities;
console.log(entities);
});
}
public entityList: T[];
constructor(public navCtrl: NavController, public navParams: NavParams)
{
}
navigateToDetail(id: number) {
console.log('test ' + id)
this.navCtrl.push(this.detailPageType, { id })
}
}
然后我修改页面以接受我们的依赖项的具体实现,
export class UsersPage {
public userDetailType: any = ProfilePage;
constructor(public navCtrl: NavController, public navParams: NavParams, public baseProvider: Users) {
console.log(this.userType);
}
}
然后我像这样实现组件:
<ion-content padding>
<page-list-base [detailPageType]="userDetailType"
[baseProvider]="baseProvider"></page-list-base>
</ion-content>