I am developing a frontend of my smart contract using Angular 8 and web3 version 1.2.7
.
When I enter the view my web3 service gets created. In the constructor I check if the window.ethereum
object exists. If yes I want to set some variables according to the networkVersion, but sometimes networkVersion is undefined and the behavior of the website is then undefined too.
I have no idea why window.ethereum
exists but networkVersion is undefined. Maybe I call it to early before the provider (in my case Metamask) can set the values.
Does anyone face the same problem and has a solution for that?
Web3Service.ts
constructor(private snackBar: MatSnackBar, private dialog: MatDialog) {
if (typeof window.ethereum !== 'undefined') {
this.web3 = new Web3(window.web3.currentProvider);
// Here networkVersion sometimes undefined
this.networkId = +window.ethereum.networkVersion;
if (this.networkId === 1) {
this.apiPath = environment.apiPathMainnet;
this.tokenContract = new this.web3.eth.Contract(artifacts.abi, environment.mainnetContractAddress);
} else if (this.networkId === 3) {
this.apiPath = environment.apiPathRopsten;
this.tokenContract = new this.web3.eth.Contract(artifacts.abi, environment.ropstenContractAddress);
} else {
this.apiPath = environment.apiPathRopsten;
this.networkNotSupported();
}
}
}