同一自定义指令 Angular2 多次出现



我目前正在构建一个 Angular 应用程序,我试图在指令(作为组件(的帮助下使代码高度可重用。

<div class="container container-fluid" >
<div class="row">
<table class="table table-responsive table-hover">
<thead class="thead-inverse">
<tr>
<th *ngFor="let column of columns">{{column.header}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of rows;trackBy: trackByID;">
<td *ngFor="let column of columns">{{row[column.field]}}
</td>
</tr>
</tbody>
</table>
</div>
<xfd-progressbar></xfd-progressbar>
<div class="row col-lg-offset-5">
<ngbd-pagination-basic></ngbd-pagination-basic>
</div>
</div>

以上是我创建的具有可重用表的指令。我的总体要求是每页有一个表格。

这是相同的相应组件 -

import {Column} from "../models/Column";
import {Component, OnInit} from "@angular/core";
import {PaginationService} from "../services/PaginationService";
import {GridLoadUtil} from "../util/GridLoadUtil";
import {ProgressBarService} from "../services/ProgressBarService";
/**
* Created by ppandey on 6/12/2017.
*/
@Component({
selector: 'xfd-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit{
columns: Column[]= [];
rows: any[] = [];
constructor(private paginService: PaginationService,
private tableLoader: GridLoadUtil,
private progressBarService: ProgressBarService) {
this.paginService.itemsToDisplayChange.subscribe((value) => {
this.rows = value
});
this.tableLoader.columnsChange.subscribe((values) => {
this.columns = values;
});
}
ngOnInit() {
this.tableLoader.beforeDataLoaded();
this.progressBarService.startProgress();
}
}

如您所见,我的组件使用Services(GridLoadUtil(为其提供数据,这使得代码高度分离。

这就是我陷入泡菜的地方。如果我想在单个页面上使用不同的数据和结构来包含多个表,则不能,因为每个组件绑定到的服务是 Singleton。

我可以选择不注入服务,并将每个服务作为 setter 提供,但在这种情况下,我需要为每个服务创建子类,而目前我不需要这样做。此外,我的代码将变得耦合。

你们认为我有什么方向可以解决这个问题吗?

谢谢 普拉提克

您可以创建一个指令来在那里提供服务。 Angulars DI 在查找TableLoader服务时会找到该提供程序,因为它最接近组件(如果组件本身不提供(:

@Directive({
selector: [tableLoader1],
providers: [{provide: GridLoadUtil, useClass: GridLoadUtil1}],
})
class TableLoader1Directive {}
@Directive({
selector: [tableLoader2],
providers: [{provide: GridLoadUtil, useClass: GridLoadUtil2}],
})
class TableLoader2Directive {}

然后你可以像使用它一样

<xfg-table tableLoader1></xfg-table>
<xfg-table tableLoader2></xfg-table>

最新更新