Encountering a "ReferenceError: global is not defined" in Angular 8 while attempting to establish a connection between my client application and Ethereum blockchain

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:

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)

Answer №1

Every time I utilized the web3 term, an error would pop up. After doing some research and reading a few articles, I finally found the solution.

To fix the global error stating that "global is not defined," you need to add the following code snippet in the file polyfill.js located within the src directory:

(window as any).global = window;
global.Buffer = global.Buffer || require('buffer').Buffer;
global.process = require('process');

Initially, try adding only the first line of this code snippet as it usually resolves the global error related to the window object.

After resolving the global error, you may encounter a new error saying "buffer is not defined." Adding the second line from the code snippet should resolve this issue.

Following the resolution of the buffer error, you might face another error related to 'process is not defined.'

You may also come across the error message "

Cannot read property 'slice' of undefined
" after tackling those initial errors.

In my case, implementing this code snippet resolved all the issues for me.

For more information, you can visit: https://github.com/angular/angular-cli/issues/9827#issuecomment-386154063

Answer №2

To establish a connection with the service provider, follow these steps:


  if (typeof window.ethereum !== 'undefined') {
      this.ethereum = new Ethereum(window.ethereum.currentProvider);
    } else {
      console.log('No ethereum? You should try using MetaMask!');
      Ethereum.providers.HttpProvider.prototype.sendAsync = Ethereum.providers.HttpProvider.prototype.send;
      this.ethereum = new Ethereum(new Ethereum.providers.HttpProvider('http://localhost:8545'));
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How do you implement an asynchronous validator for template-driven forms in Angular 2?

I have created a custom directive for my asynchronous validator: @Directive({ selector: '[validatorUsername]', providers: [{ provide: NG_ASYNC_VALIDATORS, useExisting: ValidatorUsernameDirective, multi: true }] }) export class ValidatorUsern ...

Parsing values from deeply nested objects and arrays

I've come across this issue before, but I'm having difficulty navigating through a nested structure. I can't seem to find any guidance in the right direction. Here is the object I'm attempting to parse: const nestedArray = { id ...

agm-polygon fails to refresh with new points added

I've recently switched from using Google maps to AgmMaps and wanted to create a simple demo for drawing polygons on the map. Here's what I added to my project: You can find the stackblitz link with the code here <agm-polygon [strokeColor]="& ...

What is the best way to elucidate this concept within the realm of TypeScript?

While diving into my ts learning journey, I came across this interesting code snippet: export const Field:<T> (x:T) => T; I'm having trouble wrapping my head around it. It resembles the function definition below: type myFunction<T> = ...

Using Class as a Parameter

I recently started using TypeScript and encountered an implementation issue. I'm working on a class that takes another class as an argument. The challenge is that it can be any class, but I want to define certain possible class properties or methods. ...

What are the steps to ensure a successful deeplink integration on iOS with Ionic?

Recently, I was working on a hybrid mobile app for Android/iOS using Nuxt 3, TypeScript, and Ionic. The main purpose of the app is to serve as an online store. One important feature involves redirecting users to the epay Halyk website during the payment pr ...

Refresh child route independently without relying on data from parent route

I am currently facing an issue with my component 'panel' that has two child routes: dashboard and holidays. Both of these child routes are supposed to receive data from the parent component service in their ngOnInit. While everything is working ...

Strategies for effectively choosing this specific entity from the repository

Is it possible to choose the right entity when crafting a repository method using typeorm? I'm facing an issue where I need to select the password property specifically from the Admin entity, however, the "this" keyword selects the Repository instead ...

A guide on displaying data from objects containing arrays in React using TypeScript

Hey there! I'm currently facing a challenge in rendering values within an object containing arrays. Let me show you an example of the object structure: data { info1: [{note: "this is note 1", status: true}], info2: [{note: "this i ...

Tips for preventing redundancy in Angular 2 form code

When developing my reactive forms, I always make sure to include specific properties and methods: @Input() public form: FormGroup; public messages = VALIDATION_MESSAGES; @Output() public onFormSubmit: EventEmitter<any> = new EventEmitter ...

What advantages does asynchronous microservices communication offer when it comes to enhancing the user interface experience?

When working with my Angular UI, I make a call to an API gateway endpoint like this: this.http.post(`/order`).subscribe(order => addNewOrderToList(order)); Following best practices in microservices architecture, the /order handler should publish an ev ...

A guide on implementing Angular ngbPopover within a CellRenderer for displaying in an ag-grid cell

I successfully set up an Angular Application and decided to utilize ag-grid community as a key component for displaying data from a backend API in tables, using fontawesome icons to enhance readability. While everything looks fine and my application is fu ...

Running Angular 2 build files with express.js: A step-by-step guide

Currently, I am trying to run index.html which is generated from an Angular2 app after using ng build. I attempted to use the following two lines of code individually, but unfortunately, neither of them worked for me: 1. app.use(express.static(path.resolv ...

Determining the return type of a function by analyzing its argument(s)

I'm interested in defining a method within a class that will have its type based on the argument provided in the constructor. For example: class A { private model: any; constructor(model: any) { this.model = model; } getModel( ...

Encountering the error message: ERESOLVE unable to solve dependency tree while trying to install

I'm encountering an error when attempting to install a dependency. How can I resolve this issue? npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" cla ...

Define variables using specific class components only

Consider a scenario where we define a class as follows: class House { street: string; pools: number; helicopterLandingPlace: boolean; } Now, I have created a service to update my house. putHouse(house: House) { // some put request } How ...

Incorporating Angular views as peer components within the current view

I am currently working on implementing this HTML structure: <tr *ngFor="let row of rows"> <expandable-tree-row [columns]="cols" [data]="row"></expandable-tree-row> </tr> Within the ExpandableTreeRo ...

Combining subclasses in TypeScript

Do you need help with a tricky situation? ...

How to extract a value from a BehaviorSubject within an Angular 6 guard

I have chosen this approach because I have another guard responsible for validating the user based on a token that was previously stored. This is how it was handled in previous versions of rxjs, but now with the latest version you can no longer use map on ...

Struggling to convert my VueJS component from JavaScript to TypeScript, feeling a bit lost

I am new to VueJS and I am facing a challenge converting my VueJS project to use TypeScript. I have been trying to bind functions to certain variables in JavaScript, but I am struggling with accomplishing the same in TypeScript. Even though there are no er ...