import '../../rxjs-extensions';
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { NgRedux, select } from '@angular-redux/store';
import { IAppState } from '../../store/state/AppState';
import { Logger } from '../../common/mw.common.module';
import { UiActions } from 'app/common/ui.actions/ui.actions';
import { FileActions } from './file.actions';
@Injectable()
export class FileService {
@select(['file', 'fileList']) storeFileList$;
constructor (
public http: Http,
public router: Router,
public ngRedux: NgRedux<IAppState>,
public logger: Logger,
public fileActions: FileActions,
public uiActions: UiActions
) {}
public getFileList(baseUrl: string): void {
this.storeFileList$.subscribe(fileList => {
if (fileList.files || fileList.pending) {
return;
}
const url = `${baseUrl}filelist.txt`;
this.fileActions.setFileListPending(true);
this.http.get(url)
.map((res: Response) => res.text().replace(/\r/, '').split(/\n/))
.map(files => files.filter(file => file)) // remove blank lines
.catch(error => this.handleFileListError(error))
.subscribe(files => this.fileActions.setFileListSuccess(files));
});
}
public getFile(url: string): Observable<Response> {
return this.http.get(url)
.catch(error => this.handleError(error, 'getFile'));
}
private handleFileListError(error: Response | any) {
this.fileActions.setFileListFailed(error);
const caller = `${this.constructor.name}.getFileList`;
const msg = `Caller: ${caller}, ${error}. Error status: ${error.status} }`;
error.caller = caller;
Eif (error.status === 404) {
this.uiActions.setFour0FourMessage(caller, msg, error.url);
this.router.navigate(['/404'] );
}
return Observable.throw(error);
}
private handleError(error: Response | any, method: string) {
Iif (method === 'getFileList') {
this.fileActions.setFileListFailed(error);
}
const caller = `${this.constructor.name}.${method}`;
const msg = `Caller: ${caller}, ${error}. Error status: ${error.status} }`;
error.caller = caller;
if (error instanceof Response && error.status === 404) {
this.ngRedux.dispatch( {
type: UiActions.FOUR0FOUR_MESSAGE,
four0four: { caller: caller, url: error.url }
});
this.router.navigate(['/404'] );
}
return Observable.throw(error);
}
}
|