zgo/src/app/fullnode.service.ts

79 lines
2.9 KiB
TypeScript

import {Injectable} from '@angular/core';
import {Subject, Subscription, BehaviorSubject, Observable} from 'rxjs';
import {HttpClient, HttpParams, HttpHeaders} from '@angular/common/http';
import {UserService} from './user.service';
//import {User} from './user.model';
@Injectable({providedIn: 'root'})
export class FullnodeService{
beUrl = 'http://localhost:3000/';
private dataStore: { height: number, memoList: string[], addr: string, price: number } = { height: 0, memoList: [], addr: '', price:0 };
private _heightUpdated: BehaviorSubject<number> = new BehaviorSubject(this.dataStore.height);
private _memoUpdated: BehaviorSubject<string[]> = new BehaviorSubject(this.dataStore.memoList);
private _addrUpdated: BehaviorSubject<string> = new BehaviorSubject(this.dataStore.addr);
private _priceUpdated: BehaviorSubject<number> = new BehaviorSubject(this.dataStore.price);
public readonly addrUpdate: Observable<string> = this._addrUpdated.asObservable();
public readonly heightUpdate: Observable<number> = this._heightUpdated.asObservable();
public readonly memoUpdate: Observable<string[]> = this._memoUpdated.asObservable();
public readonly priceUpdate: Observable<number> = this._priceUpdated.asObservable();
private UserSub: Subscription = new Subscription();
private apiKey = 'Le2adeic8Thah4Aeng4daem6i';
private reqHeaders: HttpHeaders;
constructor(private http: HttpClient, public userService: UserService){
this.reqHeaders = new HttpHeaders().set('Authorization', this.apiKey);
this.getAddr();
this.getHeight();
this.getPrice();
}
getHeight(){
let obs = this.http.get<{message: string, height: number}>(this.beUrl+'api/blockheight', { headers: this.reqHeaders });
obs.subscribe((BlockData) => {
this.dataStore.height = BlockData.height;
this._heightUpdated.next(Object.assign({}, this.dataStore).height);
});
return obs;
}
getPrice(){
var currency = 'usd';
const params = new HttpParams().append('currency', currency);
let obs = this.http.get<{message: string, price: any}>(this.beUrl+'api/price', { headers:this.reqHeaders, params: params, observe: 'response'});
obs.subscribe((PriceData) => {
if (PriceData.status == 200) {
this.dataStore.price = PriceData.body!.price.price;
console.log("price", this.dataStore.price);
this._priceUpdated.next(Object.assign({},this.dataStore).price);
} else {
console.log('No price found for currency', currency);
}
});
return obs;
}
hexToString(hexString: string) {
var str = '';
for (var n=0; n < hexString.length; n +=2) {
str += String.fromCharCode(parseInt(hexString.substr(n, 2), 16));
}
return str;
}
getAddr() {
let obs = this.http.get<{message: string, addr: string}>(this.beUrl+'api/getaddr', { headers: this.reqHeaders });
obs.subscribe((AddrData) => {
this.dataStore.addr = AddrData.addr;
this._addrUpdated.next(Object.assign({}, this.dataStore).addr);
});
return obs;
}
}