繁体   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