Angular 8:“ReferenceError:全局未定义”当我尝试将客户端应用程序与我的以太坊 blckchain 连接时

1 typescript ethereum solidity angular

我正在尝试使用注入令牌 web3.ts 设置我的 web3 提供程序,该令牌由 app.component.ts 导入并用于 async ngOnInit() 中。

我已经尝试过了: https://medium.com/coinmonks/https-medium-com-alexanddanik-ethereum-dapp-with-angular-angular-material-and-ngrx-f2c91435871b 它向我显示了同样的错误。我也尝试过: https: //www.udemy.com/course/blockchain-ninja-develop-ethereum-dapp-with-angular/ 当然,它向我显示了同样的错误。

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!');
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

应用程序组件.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);
}
Run Code Online (Sandbox Code Playgroud)

--- 控制台错误 ---

    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)
Run Code Online (Sandbox Code Playgroud)

小智 5

每当我使用该web3关键字时,我都会遇到同样的错误,在阅读了一些文章后我得到了答案。

polyfill.js在位于内部的文件中src添加代码片段。

(window as any).global = window;
global.Buffer = global.Buffer || require('buffer').Buffer;
global.process = require('process');
Run Code Online (Sandbox Code Playgroud)

首先,您可以尝试仅添加代码的第一行,这很可能解决 window 的全局错误global is not defined

我添加了其他代码行,因为解决全局错误后,buffer is not defined很可能会出现新的错误。

添加第二行来解决此错误后,将出现一个与进程相关的新错误process is not defined

Cannot read property 'slice' of undefined在这些错误之后。

但对我来说,这段代码完成了所有工作。

更多信息: https://github.com/angular/angular-cli/issues/9827#issuecomment-386154063