【问题标题】:How to pass a JSON from Angular 7 to a Datatable component如何将 JSON 从 Angular 7 传递到 Datatable 组件
【发布时间】:2019-08-28 10:09:59
【问题描述】:

我正在使用 Angular7 和 Datatables 库:https://datatables.net/

我想将后端 .ts 文件中的数据传递给从端组件

我的 html 看起来像这样:

  <table   datatable class="table table-striped dataTable"   [dtTrigger]="dtTrigger" [dtOptions]="dtOptions"  >
  <thead>
    <tr>
      <th>Sort</th>
      <th>Icon</th>
      <th>Title</th>
      <th>id</th>

    </tr>
  </thead>

我的组件是这样的:

export class myComponent implements OnInit {
  @ViewChild(DataTableDirective)
  dtElement: DataTableDirective;
  dtTrigger = new Subject();
  dtOptions: DataTables.Settings = {};
    // DataTables.Settings={};
  menus_ajax:JSON;

 constructor(private myService: myService) { }
ngOnInit() {

    this.myService.getdata().subscribe((event: HttpEvent<JSON>) => {
        if (event.type === HttpEventType.Response) {
             console.log('Loading data...');
             this.data = event.body;

        }
    });


    this.dtOptions = {
           'paging':false,'ordering':false,
            'ajax':{'url': this.data,'dataSrc':''},

            'columns':[{'title':'Sort','data':'sort'},{'title':'Icon','data':'icon'},
                     {'title':'Title','data':'title'},{'title':'id','data':'id'}]
    };
    this.dtTrigger.next();

 }

【问题讨论】:

    标签: angular datatables angular7 angular-datatables


    【解决方案1】:

    我认为您可能想要请求输入响应 - https://angular.io/guide/http#requesting-a-typed-response - 这将为您提供具有所需属性的对象中的数据,并且您可以在模板中引用这些数据。

    否则,您可以尝试 2 个选项 - 1. 使用 JSON.parse() 将 JSON 转换为对象 2. 使用 res.JSON() 。可以在这里看到示例 - https://l-lin.github.io/angular-datatables/#/basic/angular-way

    要根据数据渲染模板中的 trs 和 tds,您可以参考 - https://www.beyondjava.net/how-to-use-a-javascript-datatable-in-an-angular-applicationhttps://l-lin.github.io/angular-datatables/#/basic/angular-way

    他们展示了使用组件属性渲染 trs 和 tds。

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-01
      • 2019-08-11
      • 2020-09-22
      • 2019-06-10
      • 2020-04-05
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多