簡體   English   中英

如何在 datatables.net 的 table.on() function 中使用 Angular 注入服務

[英]How can I use an Angular injected service inside a table.on() function of datatables.net

我在我的 Angular 9 應用程序上使用https://datatables.net/

我的組件上有一個服務,就像這樣

constructor(private backOffice: BackofficeService) { }

然后我的 ngAfterViewInit() 上有一個 function,當我單擊數據表上的“喜歡”按鈕時觸發。


    table.on('click', '.like', function(e) {
      let $tr = $(this).closest('tr');
      console.log ($tr)
    }

我想要做的是在這個 function 中調用我的服務,以便在我的后台服務上調用一些方法來更改我的數據庫中的一些數據。 但問題是,在這種情況下, 'this'並沒有引用我的組件,而是引用了我的表格,所以我不能使用這個.backOffice.myMethod()。

我試圖實現的目標是這樣的:


    table.on('click', '.like', function(e) {
      const $tr = $(this).closest('tr');
      const data = table.row($tr).data();
      THIS.backOffice.MyMethod(data)
      .subscribe ( response => {
            console.log (response)
      });
    }

我怎樣才能做到這一點?

如果這是不可能的,我的問題是如何在我的組件中獲得 $tr 引用。html 使用 (click)="SomeOtherFunction( $tr )" 以便在沒有 table.on() function 的情況下處理此操作?

你可以嘗試如下

const backOffice = this.backOffice;

table.on('click', '.like', function(e) {
      const $tr = $(this).closest('tr');
      const data = table.row($tr).data();
      backOffice.MyMethod(data)
        .subscribe ( response => {
            console.log (response)
        });
    }

您還可以使用箭頭 function,使其指向您當前的 class,並從事件中檢索數據表

table.on('click', '.like', (e : any) => {
  const $tr = $(e.target).closest('tr');
  const data = table.row($tr).data();
  this.MyMethod(data)
    .subscribe ( response => {
        console.log (response)
    });
}

您可以在事件內訂閱服務,然后您可以通過示例刷新數據表的數據:

零件

 this.homeService.getBookingAsync().then((response: any)=>{
      this.bookResponse = response;
      this.configDataTable.data = this.bookResponse.data.results; // add results
      var table = $('#datatable').DataTable();
      table.clear().draw(); // clear current data in datatable
      table.rows.add(this.bookResponse.data.results); //set data to datatable
      table.columns.adjust().draw(); //draw new set data 
      Swal.close(); //ignore this
    });

Service 


public async getBookingAsync() {
    let filter  = this.constructGetUrl();
    filter = filter + this.setColumsToFilter();
    filter = filter + this.completeUrl(filter);
    let fullUrl = `${BASE_URL}/${API_URL}${filter}`;
    const result = await this.httpClient.get(fullUrl).toPromise(); // get with promise
    return result;
 }


DataTable Configuration

export class DataTableConfiguration {
  responsive :boolean;
  scrollY:string;
  scrollCollapse: boolean;
  data: any;
  columns:  any;
  pagingType: string;
  pageLength: number;
  processing: boolean;
  searching: boolean;
  dom: string;
  buttons:any;
  columnDefs:any;
}

我希望那可以幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM