Skip to main content
1 de 2

Service para angular 7 ` import { Observable, Subject, Observer, } from 'rxjs'; import {map} from 'rxjs/operators'

interface IbitcoinRecibidos { saldo: number; hash: string; confirmaciones:number; }

const BLOCKCHAIN_URL = "wss://ws.blockchain.info/inv";

class RecibiendoPagos {

public wallet=['14EFnam7mxMZCvUWDG8urRK7CANbi5mab6'];

private subject: Subject; public messages: Subject; public hash:string=''; public saldo:number=0; public confirmaciones:number=0;

router:Router; constructor(){ this.subject = this.create(BLOCKCHAIN_URL); this.router =Router();

 this.messages = <Subject<IbitcoinRecibidos>>
  this.connect(BLOCKCHAIN_URL)
.pipe(
  map((response: MessageEvent):IbitcoinRecibidos => {
    
    let data = JSON.parse(response.data);
    const salida = data.x.out;
    const cuentasalida = salida.length;
    this.hash = data.x.hash;

    for(let i=0; i<cuentasalida; i++){
      var direccion = data.x.out[i].addr;
      if(direccion == this.wallet){
        const monto = data.x.out[i].value;
        this.saldo = monto / 100000000;
      }}
      return {
        saldo: this.saldo,
        hash: this.hash,
        confirmaciones:this.confirmaciones
      };
  }
));

}

public connect(BLOCKCHAIN_URL:string):Subject { if (!this.subject) { this.subject = this.create(BLOCKCHAIN_URL); console.log("Successfully connected: " + BLOCKCHAIN_URL); } return this.subject; }

private create(BLOCKCHAIN_URL:string): Subject { let ws = new WebSocket(BLOCKCHAIN_URL);

let observable = Observable.create((obs: Observer<MessageEvent>) => {
  ws.onmessage = obs.next.bind(obs);
  ws.onerror = obs.error.bind(obs);
  ws.onclose = obs.complete.bind(obs);
  return ws.close.bind(ws);
});
let observer = {
  
  next: () => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(
        JSON.stringify({"op":"addr_sub","addr":this.wallet})
      );
    }
  }
};
return Subject.create(observer, observable);

} }`