繁体   English   中英

angular uing web3中如何连接钱包MetaMask?

[英]How to connect with wallet MetaMask in angular uing web3?

我正在angular中实现代码以在单击按钮时连接加密钱包,我还安装了web3 ,但我不知道如何删除错误并使用代码 init。

connectWallet(){

    let web3; 
    let ethereum = window.ethereum;

    if (typeof window.web3 !== 'undefined') {
         web3 = new Web3(window.web3.currentProvider);
      } else {
         web3 = new Web3.providers.HttpProvider(localprovide);
      }

     // ethereum = new Web3(window.ethereum);

     ethereum.enable().then(async (accounts) => {
       // console.log('transfer called.........', accounts[0]);
        localStorage.setItem('account', accounts[0]);
      });

      if (window.web3) {
        // Subscription register
        ethereum.on('accountsChanged', async (accounts) => {
            // Reload to avoid MetaMask bug: "MetaMask - RPC Error: Internal JSON-RPC"
            window.location.reload();
        });

        window.ethereum.on('networkChanged', async (network) => {
            window.location.reload();
        });
    }
}

在应用程序组件 OnInit 中:

declare const web3: any;
declare const Web3: any;

  public ngOnInit() {
    if (typeof web3 !== 'undefined') {
      // Use Mist/MetaMask's provider
      this.web3Service.web3Instance = new Web3(web3.currentProvider);
      this.web3Service.initContractInstance();

    } else {
      // Handle the case where the user doesn't have web3. Probably
      // show them a message telling them to install Metamask in
      // order to use our app.
    }
  }

Web3服务:

@Injectable()
export class Web3Service {
  private contractAddress = "your Contract Address";
  public contractInstance: any;
  public web3Instance: any;


  public initContractInstance() {
    this.contractInstance = new this.web3Instance.eth.Contract(ABI, this.contractAddress);
  }

  public getAccounts(): Promise<any> {
    return this.web3Instance.eth.getAccounts()
  }

  public signUp(account: string): Promise<any> {
    return this.contractInstance.methods.signUp()
      .send({ from: account, value: this.web3Instance.utils.toWei(PRICES.signUp, 'ether') })
  }
}

在要调用一些需要帐户的方法的组件中:

export class WelcomeComponent implements OnInit {

  constructor(private web3Service: Web3Service) {
  }

  ngOnInit(): void {
  }

  public connectWallet() {
    if (!ethEnabled()) {
      console.log("Need to download Wallet")
    } else {
      from(this.web3Service.getAccounts())
        .subscribe(accounts => {
          this.web3Service.signUp(accounts[0])
            .then(result => {
              console.log(result)
            })
        })
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM