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

43 lines
1.3 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-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-20 20:51:14 +00:00
constructor(private http: HttpClient){
}
getItems(addr: string){
2021-10-21 21:23:33 +00:00
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');
});
return obs;
2021-10-20 20:51:14 +00:00
}
}