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

58 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-10-20 20:51:14 +00:00
import { Item } from './item.model';
import { Injectable } from '@angular/core';
2021-10-21 21:23:33 +00:00
import { Subject, BehaviorSubject, Observable } from 'rxjs';
import { HttpClient, HttpParams } from '@angular/common/http';
2021-10-20 20:51:14 +00:00
@Injectable({providedIn: 'root'})
export class ItemService{
2021-11-08 20:37:26 +00:00
beUrl = 'http://localhost:3000/';
2021-10-21 21:23:33 +00:00
private dataStore: { items: Item[] } = { items: [] } ;
private _itemsUpdated: BehaviorSubject<Item[]> = new BehaviorSubject(this.dataStore.items);
public readonly itemsUpdated: Observable<Item[]> = this._itemsUpdated.asObservable();
2021-10-28 18:22:54 +00:00
private address:string = '';
2021-10-20 20:51:14 +00:00
constructor(private http: HttpClient){
}
getItems(addr: string){
2021-10-28 18:22:54 +00:00
this.address = addr;
2021-10-21 21:23:33 +00:00
const params = new HttpParams().append('address', addr);
2021-11-08 20:37:26 +00:00
let obs = this.http.get<{message: string, items: any}>(this.beUrl+'api/getitems', { headers:{}, params: params, observe: 'response'});
2021-10-21 21:23:33 +00:00
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) {
2021-10-27 12:59:43 +00:00
//const params = new HttpParams().append('item', JSON.stringify(item));
2021-11-08 20:37:26 +00:00
let obs = this.http.post<{message: string}>(this.beUrl+'api/item', { item: item });
obs.subscribe((ItemResponse) => {
console.log('Item added');
2021-10-28 18:22:54 +00:00
this.getItems(this.address);
});
return obs;
2021-10-20 20:51:14 +00:00
}
2021-10-26 18:34:52 +00:00
deleteItem(id: string) {
2021-11-08 20:37:26 +00:00
let obs = this.http.delete<{message: string}>(this.beUrl+'api/item/'+id);
2021-10-26 18:34:52 +00:00
obs.subscribe((ItemResponse) => {
console.log('Item deleted');
2021-10-28 18:22:54 +00:00
this.getItems(this.address);
2021-10-26 18:34:52 +00:00
});
return obs;
}
2021-10-20 20:51:14 +00:00
}