Services
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Tcp } from '../tcp/tcp';
import { Subject } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class TcpService {
private tcps: Tcp[] = [];
private tcpsUpdated = new Subject<Tcp[]>();
uri = 'http://localhost:3000/api/tcps';
constructor(private http: HttpClient) { }
getTcps(){
this.http
.get<{ message: string; tcps: any }>(
this.uri
)
.pipe(map((tcpData) => {
return tcpData.tcps.map(tcp => {
return {
registro: tcp.regtcp,
nivel: tcp.niveltcp,
nome: tcp.nometcp,
id: tcp._id
};
});
}))
.subscribe(transformedTcps => {
this.tcps = transformedTcps;
this.tcpsUpdated.next([...this.tcps]);
});
}
getTcpUpdateListener() {
return this.tcpsUpdated.asObservable();
}
addTcp(nometcp: string, regtcp: Number,niveltcp:Number) {
const tcp: Tcp = { id: null, nometcp: nometcp, regtcp: Number(regtcp),niveltcp: Number(niveltcp) };
this.http
.post<{ message: string, tcpId: string }>(this.uri, tcp)
.subscribe(responseData => {
const id = responseData.tcpId;
tcp.id = id;
this.tcps.push(tcp);
this.tcpsUpdated.next([...this.tcps]);
});
}
deleteTcp(tcpId: string) {
this.http.delete(this.uri + tcpId)
.subscribe(() => {
const updatedTcps = this.tcps.filter(tcp => tcp.id !== tcpId);
this.tcps = updatedTcps;
this.tcpsUpdated.next([...this.tcps]);
});
}
}