Yangman - changed exporting of collections
[dlux.git] / modules / yangman-resources / src / main / resources / yangman / services / handle-file.services.js
1 define([], function () {
2     'use strict';
3
4     angular.module('app.yangman').service('YMHandleFileService', YMHandleFileService);
5
6     YMHandleFileService.$inject = ['$window'];
7
8     function YMHandleFileService($window){
9         var service = {
10             downloadFile: downloadFile,
11         };
12
13         return service;
14
15         /**
16          * Service for preparing file and creating link for downloading
17          * @param filename
18          * @param data
19          * @param format
20          * @param charset
21          * @param successCbk
22          * @param errorCbk
23          */
24         function downloadFile(filename, data, format, charset, successCbk, errorCbk){
25             try {
26                 var blob = new Blob([JSON.stringify(data, null, 4)], { type: 'application/' + format + '; ' + charset + ';' }),
27                     downloadLink = angular.element('<a></a>');
28
29                 var clickEvent = new MouseEvent('click', {
30                     'view': window,
31                     'bubbles': true,
32                     'cancelable': false
33                 });
34
35                 downloadLink.attr('href', window.URL.createObjectURL(blob));
36                 if(downloadLink.attr('download', filename) !== undefined) {
37                     downloadLink[0].dispatchEvent(clickEvent);
38                     successCbk();
39                 }
40                 else {
41                     $window.location.href = downloadLink[0].href;
42                 }
43             } catch (e) {
44                 errorCbk(e);
45             }
46         }
47     }
48 });