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

79 lines
2.3 KiB
TypeScript
Raw Normal View History

2018-03-07 11:56:50 +01:00
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';
2017-05-10 11:04:06 +02:00
@Injectable()
export class UserService {
users$: Observable<User[]>;
2017-10-14 15:26:05 +02:00
totalCount = 0;
2017-05-10 11:04:06 +02:00
constructor(private http: HttpClient,
private userStore: UserStore,
private config: AppConfig) {
this.users$ = userStore.items$;
}
2017-10-14 17:47:55 +02:00
findUsers(query = '', fractionFilter?, squadFilter?, limit?, offset?, action = LOAD) {
2017-05-10 11:04:06 +02:00
const searchParams = new URLSearchParams();
searchParams.append('q', query);
if (fractionFilter) {
searchParams.append('fractFilter', fractionFilter);
}
2017-06-09 18:30:35 +02:00
if (squadFilter) {
searchParams.append('squadId', squadFilter);
}
2017-10-14 15:26:05 +02:00
searchParams.append('limit', limit);
searchParams.append('offset', offset);
this.http.get(this.config.apiUserPath, searchParams)
2018-02-26 09:04:27 +01:00
.do((res) => {
let headerCount = parseInt(res.headers.get('x-total-count'));
if (headerCount) {
this.totalCount = headerCount;
}
}).map(res => res.json()).do((users) => {
2017-10-14 17:47:55 +02:00
this.userStore.dispatch({type: action, data: users});
2018-02-26 09:04:27 +01:00
}).subscribe(_ => {
});
2017-05-10 11:04:06 +02:00
return this.users$;
}
getUser(_id: number | string): Observable<User> {
return this.http.get(this.config.apiUserPath + _id)
2018-02-26 09:04:27 +01:00
.map(res => res.json());
2017-05-10 11:04:06 +02:00
}
submitUser(user) {
return this.http.post(this.config.apiUserPath, user)
2018-02-26 09:04:27 +01:00
.map(res => res.json())
.do(savedUser => {
const action = {type: ADD, data: savedUser};
this.userStore.dispatch(action);
});
2017-05-10 11:04:06 +02:00
}
updateUser(user) {
return this.http.put(this.config.apiUserPath + user._id, user)
2018-02-26 09:04:27 +01:00
.map(res => res.json())
.do(savedUser => {
const action = {type: EDIT, data: savedUser};
this.userStore.dispatch(action);
});
2017-05-10 11:04:06 +02:00
}
deleteUser(user) {
return this.http.delete(this.config.apiUserPath + user._id)
2018-02-26 09:04:27 +01:00
.do(res => {
this.userStore.dispatch({type: REMOVE, data: user});
});
2017-05-10 11:04:06 +02:00
}
}