網站搜尋

angular - 如何製作一個調用不同服務的通用方法


我正在使用 Angular,並且有這個方法:

  loadPagedRecords() {
    this.loadingSpinner = true;
    this.subPage = this.administratorService.getPage(AppSettings.RECORDS_PER_PAGE)
      .subscribe(resp => {
        this.page.recordsList = resp.content;
        this.page.totalElements = resp.totalElements;

        this.pager = this.pagerService.getPager(this.page.totalElements, 1, AppSettings.RECORDS_PER_PAGE);
        this.pagedItems = this.page.recordsList.slice(this.pager.startIndex, this.pager.endIndex + 1);

        this.loadingSpinner = false;
      }, (error) => {
        this.loadingSpinner = false;
      });
  }

此方法負責在其列表組件中加載所有管理員的記錄。問題是我還有其他列表組件(客戶、服務、付款),並且我在所有這些組件中重複了相同的方法(不同之處是將調用的服務)。

我想做的是創建一個帶有此方法的抽象類,但它訂閱的變量需要是泛型的。在上面的例子中,它對 administratorService 進行了訂閱。

我如何才能使它通用,以便適用於我所有的列表元件?

編輯:

我做了一些更改,現在這個方法按我想要的方式運作了……但不確定這是否是一個好的解決方案:

export abstract class BaseList {

       constructor(protected service: any, protected pagerService: any) {}

  loadPagedRecords() {
    this.loadingSpinner = true;
    this.subPage = this.service.getPage(AppSettings.RECORDS_PER_PAGE)
      .subscribe(resp => {
        this.page.recordsList = resp.content;
        this.page.totalElements = resp.totalElements;

        this.pager = this.pagerService.getPager(this.page.totalElements, 1, AppSettings.RECORDS_PER_PAGE);
        this.pagedItems = this.page.recordsList.slice(this.pager.startIndex, this.pager.endIndex + 1);

        this.loadingSpinner = false;
      }, (error) => {
        this.loadingSpinner = false;
      });
  }


}

export class ListAdministratorsComponent extends BaseList implements OnInit {

  constructor(private titleService: Title, private router: Router,
    protected administratorsService: AdministratorsService,
    protected pagerService: PagerService,
    private toastrService: ToastrService
  ) { 
       super(administradoresService, pagerService); 
    }

  ngOnInit() {
       this.loadPagedRecords();
  }

}

你覺得怎麼樣?

答案#1

由於不清楚你應用程式的具體結構,所以我無法說是否有更好的方法,但你可以考慮使用抽象類別:

export abstract class RecordViewer<T> {
  abstract readonly serviceGetter = (...args?: any[]) => Observable<T>;

  loadPagedRecords() {
    this.loadingSpinner = true;
    this.subPage = this.serviceGetter(AppSettings.RECORDS_PER_PAGE).pipe(
      finalize(() => this.loadingSpinner = false)
    ).subscribe(resp => {
      this.page.recordsList = resp.content;
      this.page.totalElements = resp.totalElements;
      this.pager = this.pagerService.getPager(
        this.page.totalElements, 1, AppSettings.RECORDS_PER_PAGE
      );
      this.pagedItems = this.page.recordsList.slice(
        this.pager.startIndex, this.pager.endIndex + 1
      );
    });
  }
}

然後你可以從你的元件擴充它:

export class AdministratorComponent extends RecordViewer<Administrator> {
  readonly serviceGetter = this.administratorService.getPage;

  constructor(private administratorService: AdministratorService) {}
}