Inject Web3 in Angular 7.0

Don’t instantiate it the wrong way anymore

GrandSchtroumpf
B2Expand
2 min readJul 31, 2018

--

I would like to suggest an angular-ish way to inject web3 library in your Angular 7 application.

UPDATE : The code has been updated to reflect how MetaMask works now.

The wrong way

Most of the time, web3 is instantiated as a property of a service that would deal with all the eth logic (Contracts are usually separated services). It looks something like this:

The good thing about that is that you can encapsulate the Promise based functions you want to use in your app with an Observable structure.

But it feels wrong to me to instantiate a singleton class as a property of a service. Beside, you’ll need to create new methods each time you want to use another web3 method, which is insane…. 😱

The old way

In a previous article I suggested another way to use web3 as a dependency singleton that you can used throughout your app:

We create an injection token WEB3 that will be used to get the instance of Web3 in our Injector. For that I created an EthereumModule class which provides the instance with the useFactory function.

Then you can use the web3 library as it, by injecting it in your components or services with @Inject:

It feels better 😉, but we can do even better with Angular 6.

The new (and best 😍) way

Angular 6 introduced the providedIn option of the @Injectable decorator. This help to tree-shake your app, and inject the service directly in your bootstrapped module (if you set it to ‘root’). Here is how you can use the previous InjectionToken with Angular 6:

web3.ts

And here we are! ✨
A very convenient way to add our web3 singleton as a dependency for our app. The power of web3 is at your fingertips anywhere in your Dapp.

Update:

This code use the new way to connect to the MetaMask. The first time you use this token in your code you should call the enablemethod of window.ethereum :

Hope you’ll find it useful for your projects.

--

--

GrandSchtroumpf
B2Expand

I co-founded DappsNation, a Blockchain studio that build awesome decentralized applications. I also work at the Ethereum Foundation for the Remix project.