opt-cc/static/src/app/services/army-management/user.service.ts

79 lines
2.3 KiB
TypeScript

import {Injectable} from '@angular/core';
import {User} from '../../models/model-interfaces';
import {URLSearchParams} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {ADD, EDIT, LOAD, REMOVE, UserStore} from '../stores/user.store';
import {AppConfig} from '../../app.config';
import {HttpClient} from '../http-client';
@Injectable()
export class UserService {
users$: Observable<User[]>;
totalCount = 0;
constructor(private http: HttpClient,
private userStore: UserStore,
private config: AppConfig) {
this.users$ = userStore.items$;
}
findUsers(query = '', fractionFilter?, squadFilter?, limit?, offset?, action = LOAD) {
const searchParams = new URLSearchParams();
searchParams.append('q', query);
if (fractionFilter) {
searchParams.append('fractFilter', fractionFilter);
}
if (squadFilter) {
searchParams.append('squadId', squadFilter);
}
searchParams.append('limit', limit);
searchParams.append('offset', offset);
this.http.get(this.config.apiUserPath, searchParams)
.do((res) => {
let headerCount = parseInt(res.headers.get('x-total-count'));
if (headerCount) {
this.totalCount = headerCount;
}
}).map(res => res.json()).do((users) => {
this.userStore.dispatch({type: action, data: users});
}).subscribe(_ => {
});
return this.users$;
}
getUser(_id: number | string): Observable<User> {
return this.http.get(this.config.apiUserPath + _id)
.map(res => res.json());
}
submitUser(user) {
return this.http.post(this.config.apiUserPath, user)
.map(res => res.json())
.do(savedUser => {
const action = {type: ADD, data: savedUser};
this.userStore.dispatch(action);
});
}
updateUser(user) {
return this.http.put(this.config.apiUserPath + user._id, user)
.map(res => res.json())
.do(savedUser => {
const action = {type: EDIT, data: savedUser};
this.userStore.dispatch(action);
});
}
deleteUser(user) {
return this.http.delete(this.config.apiUserPath + user._id)
.do(res => {
this.userStore.dispatch({type: REMOVE, data: user});
});
}
}