swuecho / redashX

0 stars 0 forks source link

download renderer #41

Open swuecho opened 10 months ago

swuecho commented 10 months ago
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { GridOptions } from 'ag-grid-community';

@Component({
  selector: 'app-root',
  template: `
    <ag-grid-angular
      style="width: 600px; height: 500px;"
      class="ag-theme-alpine"
      [gridOptions]="gridOptions"
      (firstDataRendered)="onFirstDataRendered($event)"
    ></ag-grid-angular>
  `,
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  gridOptions: GridOptions = {
    columnDefs: [
      { headerName: 'Name', field: 'name' },
      { headerName: 'Age', field: 'age' },
      { headerName: 'Country', field: 'country' },
      { headerName: 'Action', field: 'action', cellRenderer: 'actionRenderer' },
    ],
    rowData: [
      { name: 'John Doe', age: 30, country: 'USA', id: 1 },
      { name: 'Jane Doe', age: 25, country: 'Canada', id: 2 },
      // Add more rows as needed
    ],
    frameworkComponents: {
      actionRenderer: ActionRendererComponent,
    },
  };

  constructor(private httpClient: HttpClient) {}

  onFirstDataRendered(params: any) {
    params.api.sizeColumnsToFit();
  }
}

@Component({
  selector: 'app-action-renderer',
  template: `
    <button (click)="onActionClick()">Download JSON</button>
  `,
})
export class ActionRendererComponent {
  constructor(private httpClient: HttpClient) {}

  agInit(params: any): void {
    // You can access row data using params.data
    // For example, params.data.id
  }

  onActionClick() {
    const apiUrl = 'your-api-endpoint?id='; // Replace with your actual API endpoint and include necessary parameters

    this.httpClient.get(apiUrl).subscribe(
      (data: any) => {
        this.downloadDataAsJson(data, 'collection.json');
      },
      (error) => {
        console.error('Error:', error);
      }
    );
  }

  downloadDataAsJson(data: any, filename: string) {
    const jsonBlob = new Blob([JSON.stringify(data)], { type: 'application/json' });
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(jsonBlob);
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}