Skip to main content

Example: Util Service

import { Injectable } from '@angular/core';
import { CurrencyPipe, DatePipe, DecimalPipe, PercentPipe } from '@angular/common';
import { isNumber } from 'util';
import { of, throwError } from 'rxjs';
import { Observable } from 'rxjs/index';
import _ from 'lodash';


@Injectable({
providedIn: 'root'
})
export class UtilService {
cp: CurrencyPipe = new CurrencyPipe('en-US');
dp: DecimalPipe = new DecimalPipe('en-US');
dtp: DatePipe = new DatePipe('en-US');
pp: PercentPipe = new PercentPipe('en-US');

constructor() { }

/**
* Generates contents of a flat file based on incoming source data.
*/
buildFlatFileContent(source: any[]): Observable<string> {
let fileContents = '';

try {
if (Array.isArray(source) && source.length) {
// Each item of source will be a string representing the entire contents of the row
fileContents = _.join(source, '\r\n');
}
} catch(e) {
console.error(e);
return throwError(new Error('There was a problem building the flat file contents.'));
}

return of(fileContents);
}

/**
* Called to download a text-based file client-side.
*/
downloadFile(filename: string, contents: string): Observable<any> {
let observable = new Observable(subscriber => {
let blob = new Blob([contents]);


if (window.navigator && window.navigator.msSaveOrOpenBlob) {
//Open file IE
window.navigator.msSaveOrOpenBlob(blob, filename);
subscriber.complete();
} else {
//Open file browser other than IE
let a = document.createElement('a');
a.style.display = 'none';
document.body.appendChild(a);
a.href = window.URL.createObjectURL(blob);
a.download = filename;

setTimeout(() => {
a.click();
document.body.removeChild(a);
subscriber.next("Success");
subscriber.complete();
}, 500);
}
});

return observable;
}

/**
* Strips currency characters from a currency formatted number
* string and returns the numeric equivalent.
*/
currencyToNumber(source: string): number {
if (!(typeof source === 'string' && source.length)) {
return NaN;
}

let modifiedSource = source.replace(/[$,]/g, '');
modifiedSource = modifiedSource.replace(/\(/, '-');
modifiedSource = modifiedSource.replace(/\)/, '');

return isNaN(Number(modifiedSource)) ? NaN : parseFloat(modifiedSource);
}

/**
* Formats the incoming bytes as a readable string.
*/
formatFileSize(bytes, decimalPoint) {
if (bytes == 0) return '0 Bytes';
let k = 1000;
let dm = decimalPoint || 2;
let sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
let i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
}