import {Injectable} from "@angular/core"; import {Squad} from "../../models/model-interfaces"; import {RequestMethod, RequestOptions, URLSearchParams} from "@angular/http"; import {Observable} from "rxjs/Observable"; import {SquadStore, ADD, EDIT, LOAD, REMOVE} from "../stores/squad.store"; import {AppConfig} from "../../app.config"; import {HttpClient} from "../http-client"; @Injectable() export class SquadService { squads$: Observable; constructor(private http: HttpClient, private squadStore: SquadStore, private config: AppConfig) { this.squads$ = squadStore.items$; } findSquads(query = '', fractionFilter='') { const searchParams = new URLSearchParams(); searchParams.append('q', query); searchParams.append('fractFilter', fractionFilter); this.http.get(this.config.apiSquadPath, searchParams) .map(res => res.json()) .do((squads) => { this.squadStore.dispatch({type: LOAD, data: squads}); }).subscribe(_ => { }); return this.squads$; } getSquad(id: number | string): Observable { return this.http.get(this.config.apiSquadPath + id) .map(res => res.json()); } /** * For creating new data with POST or * update existing with patch PATCH */ submitSquad(squad: Squad, imageFile?) { let requestUrl = this.config.apiSquadPath; let requestMethod: RequestMethod; let accessType; let body; if (squad._id) { requestUrl += squad._id; requestMethod = RequestMethod.Patch; accessType = EDIT; } else { requestMethod = RequestMethod.Post; accessType = ADD; } if (imageFile) { body = new FormData(); Object.keys(squad).map((objectKey) => { if (squad[objectKey] !== undefined) { body.append(objectKey, squad[objectKey]); } }); body.append('image', imageFile, imageFile.name); } else { body = squad; } const options = new RequestOptions({ body: body, method: requestMethod }); return this.http.request(requestUrl, options) .map(res => res.json()) .do(savedSquad => { const action = {type: accessType, data: savedSquad}; this.squadStore.dispatch(action); }); } deleteSquad(squad: Squad) { return this.http.delete(this.config.apiSquadPath + squad._id) .do(res => { this.squadStore.dispatch({type: REMOVE, data: squad}); }); } }