import { Item } from './item.model'; import { Injectable } from '@angular/core'; import { Subject, BehaviorSubject, Observable } from 'rxjs'; import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http'; var Buffer = require('buffer/').Buffer; @Injectable({providedIn: 'root'}) export class ItemService{ beUrl = 'https://test.zgo.cash/'; private dataStore: { items: Item[] } = { items: [] } ; private _itemsUpdated: BehaviorSubject = new BehaviorSubject(this.dataStore.items); public readonly itemsUpdated: Observable = this._itemsUpdated.asObservable(); private address:string = ''; private reqHeaders: HttpHeaders; constructor(private http: HttpClient){ var auth = 'Basic ' + Buffer.from('user:superSecret2').toString('base64'); this.reqHeaders = new HttpHeaders().set('Authorization', auth); } getItems(addr: string){ this.address = addr; const params = new HttpParams().append('address', addr); let obs = this.http.get<{message: string, items: any}>(this.beUrl+'api/items', { headers:this.reqHeaders, 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 { this.dataStore.items = []; this._itemsUpdated.next(Object.assign({},this.dataStore).items); 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}>(this.beUrl+'api/item', { payload: item }, { headers: this.reqHeaders }); obs.subscribe((ItemResponse) => { console.log('Item added'); this.getItems(this.address); }); return obs; } deleteItem(id: string) { let obs = this.http.delete<{message: string}>(this.beUrl+'api/item/'+id, { headers: this.reqHeaders }); obs.subscribe((ItemResponse) => { console.log('Item deleted'); this.getItems(this.address); }); return obs; } }