import {Injectable} from '@angular/core'; import {Rank} from '../../models/model-interfaces'; import {RequestMethod, RequestOptions, URLSearchParams} from '@angular/http'; import {Observable} from 'rxjs/Observable'; import {ADD, EDIT, LOAD, REMOVE, Store} from '../stores/generic-store'; import {AppConfig} from '../../app.config'; import {HttpClient} from '../http-client'; @Injectable() export class RankService { ranks$: Observable; rankStore = new Store(); constructor(private http: HttpClient, private config: AppConfig) { this.ranks$ = this.rankStore.items$; } findRanks(query = '', fractionFilter?) { const searchParams = new URLSearchParams(); searchParams.append('q', query); if (fractionFilter) { searchParams.append('fractFilter', fractionFilter); } this.http.get(this.config.apiRankPath, searchParams) .map(res => res.json()) .do((ranks) => { this.rankStore.dispatch({type: LOAD, data: ranks}); }).subscribe(_ => { }); return this.ranks$; } getRank(id: number | string): Observable { return this.http.get(this.config.apiRankPath + id) .map(res => res.json()); } /** * For creating new data with POST or * update existing with patch PATCH */ submitRank(rank: Rank, imageFile?) { let requestUrl = this.config.apiRankPath; let requestMethod: RequestMethod; let accessType; let body; if (rank._id) { requestUrl += rank._id; requestMethod = RequestMethod.Patch; accessType = EDIT; } else { requestMethod = RequestMethod.Post; accessType = ADD; } if (imageFile) { body = new FormData(); Object.keys(rank).map((objectKey) => { if (rank[objectKey] !== undefined) { body.append(objectKey, rank[objectKey]); } }); body.append('image', imageFile, imageFile.name); } else { body = rank; } const options = new RequestOptions({ body: body, method: requestMethod }); return this.http.request(requestUrl, options) .map(res => res.json()) .do(savedRank => { const action = {type: accessType, data: savedRank}; // leave some time to save image file before accessing it through listview setTimeout(() => { this.rankStore.dispatch(action); }, 300); }); } deleteRank(rank: Rank) { return this.http.delete(this.config.apiRankPath + rank._id) .do(res => { this.rankStore.dispatch({type: REMOVE, data: rank}); }); } }