I'm trying to configure my web3 provider using an injection token called web3.ts. The token is imported in the app.component.ts file and utilized within the async ngOnInit() method.
I've attempted various solutions such as:
- Medium Tutorial
- Udemy Course
Below is the code snippet for web3.ts:
import { InjectionToken } from '@angular/core';
import Web3 from 'web3';
export const WEB3 = new InjectionToken<Web3>('web3', {
providedIn: 'root',
factory: () => {
try {
const provider = ('ethereum' in window) ? window['ethereum'] : Web3.givenProvider;
return new Web3(provider);
} catch (err) {
throw new Error('Non-Ethereum browser detected. You should consider trying Mist or MetaMask!');
}
}
});
And here's a snippet from app.component.ts:
import { WEB3 } from './web3';
import Web3 from 'web3';
constructor(@Inject(WEB3) private web3: Web3) { }
async ngOnInit() {
if ('enable' in this.web3.currentProvider) {
await this.web3.currentProvider;
}
const accounts = await this.web3.eth.getAccounts();
console.log(accounts);
}
Encountered Error in Console:
capability.js:1 Uncaught ReferenceError: global is not defined
at Object../node_modules/stream-http/lib/capability.js (capability.js:1)
at __webpack_require__ (bootstrap:79)
at Object../node_modules/stream-http/lib/request.js (request.js:1)
at __webpack_require__ (bootstrap:79)
at Object../node_modules/stream-http/index.js (index.js:1)
at __webpack_require__ (bootstrap:79)
at Object../node_modules/xhr2-cookies/dist/xml-http-request.js (xml-http-request.js:21)
at __webpack_require__ (bootstrap:79)
at Object../node_modules/xhr2-cookies/dist/index.js (index.js:6)
at __webpack_require__ (bootstrap:79)