Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable } from '@angular/core';
- import { HttpClient } from '@angular/common/http';
- import { BehaviorSubject, Observable, Subject } from 'rxjs';
- import { map } from 'rxjs/operators';
- import { environment } from '../../environments/environment';
- import { Match } from '../models/match';
- import { first } from 'rxjs/operators';
- @Injectable({
- providedIn: 'root'
- })
- export class MatchService {
- private matchSource = new BehaviorSubject(new Match);
- public selectedMatchAsObservable = this.matchSource.asObservable();
- private selectedMatch : Match;
- private matchesSource = new BehaviorSubject([]);
- public matches = this.matchesSource.asObservable();
- private localMatches : Match[] = [];
- constructor(private http: HttpClient){}
- setSelectedMatch(post: Match){
- this.matchSource.next(post);
- this.selectedMatch = post;
- console.log("current selected match: " + post.title);
- }
- getSelectedMatch(){
- return this.selectedMatch;
- }
- getAll() {
- this.http.get<Match[]>(`${environment.apiUrl}/matches`).pipe(first()).subscribe(matches => {
- this.matchesSource.next(matches);
- this.localMatches = matches;
- });
- }
- getById(id: number) {
- return this.http.get(`${environment.apiUrl}/matches/` + id);
- }
- update(post: Match) {
- let postAsFormData = new FormData();
- postAsFormData.append('title', post.title);
- postAsFormData.append('swimmingPool', post.swimmingPool);
- postAsFormData.append('organiser', post.organiser);
- this.http.put<Match>(`${environment.apiUrl}/matches/` + post._id, postAsFormData).pipe(first()).subscribe(updatedPost => {
- const index = this.localMatches.indexOf(<Match> post, 0);
- if (index > -1) {
- this.localMatches[index] = updatedPost;
- }
- this.matchesSource.next(this.localMatches);
- })
- }
- delete(post: Match) {
- this.http.delete(`${environment.apiUrl}/matches/` + post._id).pipe(first()).subscribe(x => {
- const index = this.localMatches.indexOf(<Match> post, 0);
- if (index > -1) {
- this.localMatches.splice(index, 1);
- }
- this.matchesSource.next(this.localMatches);
- });
- }
- create(post: Match) {
- let postAsFormData = new FormData();
- postAsFormData.append('title', post.title);
- postAsFormData.append('swimmingPool', post.swimmingPool);
- postAsFormData.append('organiser', post.organiser);
- this.http.post(`${environment.apiUrl}/matches/`, postAsFormData).pipe(first()).subscribe(post => {
- this.localMatches.push(<Match> post);
- this.matchesSource.next(this.localMatches);
- });
- }}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement