zgo/src/app/items/items.service.ts

57 lines
1.6 KiB
TypeScript

import { Item } from './item.model';
import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject, Observable } from 'rxjs';
import { HttpClient, HttpParams } from '@angular/common/http';
@Injectable({providedIn: 'root'})
export class ItemService{
private dataStore: { items: Item[] } = { items: [] } ;
private _itemsUpdated: BehaviorSubject<Item[]> = new BehaviorSubject(this.dataStore.items);
public readonly itemsUpdated: Observable<Item[]> = this._itemsUpdated.asObservable();
private address:string = '';
constructor(private http: HttpClient){
}
getItems(addr: string){
this.address = addr;
const params = new HttpParams().append('address', addr);
let obs = this.http.get<{message: string, items: any}>('http://localhost:3000/api/getitems', { headers:{}, params: params, observe: 'response'});
obs.subscribe((ItemDataResponse) => {
if (ItemDataResponse.status == 200 ) {
this.dataStore.items = ItemDataResponse.body!.items;
this._itemsUpdated.next(Object.assign({},this.dataStore).items);
} else {
console.log('No items found');
}
});
return obs;
}
addItem(item: Item) {
//const params = new HttpParams().append('item', JSON.stringify(item));
let obs = this.http.post<{message: string}>('http://localhost:3000/api/item', { item: item });
obs.subscribe((ItemResponse) => {
console.log('Item added');
this.getItems(this.address);
});
return obs;
}
deleteItem(id: string) {
let obs = this.http.delete<{message: string}>('http://localhost:3000/api/item/'+id);
obs.subscribe((ItemResponse) => {
console.log('Item deleted');
this.getItems(this.address);
});
return obs;
}
}