Search code examples
angularfilesaver.js

FileSaver and Angular2 - not finding file on get request


I'm trying to make FileSaver work for my Angular2 project and have tried working through with the answers from other questions and still can't seem to find it.

In my service:

@Injectable()
export class DownloadsService {
    http: any;
    private actionUrl: string;
    //constructor(private _http: Http) {
    constructor(private jsonp: Jsonp, private _http: Http) {
        let hostname = document.location.hostname;
        console.log(hostname);
        if (hostname === 'localhost') {
            this.actionUrl = '/src/assets/rr/spreadsheets/';
        } else {
            this.actionUrl = '';
        }
    }

    downloadBlaBlasCSV() {
        let options = { responseType: ResponseContentType.ArrayBuffer };
        console.log(this.actionUrl + 'event_template_2.xlsx');
        return this.http
            .get(this.actionUrl + 'event_template_2.xlsx', options)
        .map((res: Response) => res['_body'])
        .catch((err: Response) => Observable.throw(err.json()));
    }

}

In my component:

import { saveAs } from 'file-saver';

    downloadBlaBlasCSV() {
        this._downloadsService.downloadBlaBlasCSV().subscribe(
          (data) => { this.openFileForDownload(data); },
          (error: any) => {});
      }

    openFileForDownload(data: Response) {
        var blob = new Blob([data], { type: 'text/xlsx;charset=utf-8' });
        saveAs(blob, 'player_template.xlsx');
      }

In my html:

<button class="btn btn-primary" (click)="downloadBlaBlasCSV()">Download Spreadsheet Template</button>

And I receive this error:

ERROR TypeError: Cannot read property 'get' of undefined
    at DownloadsService.webpackJsonp.../../../../../src/app/services/downloads.service.ts.DownloadsService.downloadBlaBlasCSV (downloads.service.ts:32)
    at PlayersComponent.webpackJsonp.../../../../../src/app/players/players.component.ts.PlayersComponent.downloadBlaBlasCSV (players.component.ts:27)
    at Object.eval [as handleEvent] (PlayersComponent.html:37)
    at handleEvent (core.es5.js:11995)
    at callWithDebugContext (core.es5.js:13456)
    at Object.debugHandleEvent [as handleEvent] (core.es5.js:13044)
    at dispatchEvent (core.es5.js:8599)
    at core.es5.js:9210
    at HTMLButtonElement.<anonymous> (platform-browser.es5.js:2651)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)

I don't know if I'm just not creating the correct URL to the assets folder or what, but I've tried many iterations of it and still get the same error. Any help would be much appreciated. Thank you.


Solution

  • The problem probably is not in FileSaver. You are writing:

    private _http: Http
    

    But you are using without _:

    this.http should be this._http