我试图让FileSaver为我的Angular2项目工作,并尝试使用其他问题的答案,但仍然无法找到它。
在我的服务中:
@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()));
}
}
在我的组件中:
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');
}
在我的HTML中:
<button class="btn btn-primary" (click)="downloadBlaBlasCSV()">Download Spreadsheet Template</button>
我收到此错误:
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)
我不知道我是不是要创建资源文件夹的正确URL或者是什么,但是我已经尝试了很多迭代,但仍然会得到相同的错误。任何帮助将非常感激。谢谢。
答案 0 :(得分:0)
问题可能不在FileSaver
中。你在写:
private _http: Http
但是你没有使用_
:
this.http should be this._http
答案 1 :(得分:0)
可以更改downloadBlaBlasCSV方法
downloadBlaBlasCSV()
{
let headers = new Headers();
headers.append('Authorization', 'JWT ' + localStorage.getItem('id_token'));
return this._http.get(url,{ headers: headers,responseType: ResponseContentType.Blob }).map(
(res) => {
return new Blob([res.blob()], { type: 'application/vnd.ms-excel' })
})
}
也请参阅此帖子angular2 file download