Skip to content

Instantly share code, notes, and snippets.

@carlosm2011
Created July 12, 2017 22:30
Show Gist options
  • Save carlosm2011/32cefa6b3cf52d7d6ab0747d19e22f18 to your computer and use it in GitHub Desktop.
Save carlosm2011/32cefa6b3cf52d7d6ab0747d19e22f18 to your computer and use it in GitHub Desktop.
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from "@angular/http";
import { Observable } from "rxjs";
import Web3 from 'web3'; /** I think this is equivalent
to the require function. I'm also doing 'web3/lib because that is where the web3.js file is*/
let web3:Web3 = new Web3();
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} /** set the provider you want from Web3.providers */
else {
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
@Injectable()
export class SharedService {
currencyURL = "http://api.fixer.io/latest?symbols=";
totReqsMade: number = 0;
constructor(private _http: Http) {
}
getBalance(Add){
return this._http.get(this.currencyURL + Add)
.map(response => {
{ return response.json() };
})
.catch(error => Observable.throw(error.json()));
}
getEtherBalance(PubAd) {
return web3.eth.getBlock(48, function(error, result){
if(!error)
console.log(result)
else
console.error(error);
})
}
/** let web3 = require('web3'); Trying to instantiate how the website says to do it.*/
}
@DeviateFish
Copy link

DeviateFish commented Jul 12, 2017

Oh, I think what might be going is that you're overwriting the global web3 with your local one in this scope.

This line is supposed to be checking to see if web3 is already defined in the global scope, but I think the line before that is breaking it.

I think it should probably be the following (feel free to change variable names):

let localWeb3:Web3;
if (typeof web3 !== 'undefined') {
  localWeb3 = new Web3(web3.currentProvider);
} /** set the provider you want from Web3.providers */
else {
  localWeb3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}

Or, if you want to keep the same naming (this one might be better anyway, due to more explicit global scoping):

let web3:Web3;
if (typeof window.web3 !== 'undefined') {
  web3 = new Web3(window.web3.currentProvider);
} /** set the provider you want from Web3.providers */
else {
  web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}

Basically, what I think is going on is that you're defining web3 in your local scope, then immediately checking to see if it exists (which it will, always), and trying to use the currentProvider from the web3 you just created (that doesn't have a provider yet)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment