Angular: Strugguling with window.ethereum? 😭🀬

Blocks Creatorz
2 min readJan 15, 2021

Hi Medium readers & bloggers this is my first ever article! Hurray πŸ₯³

Blockchain is fantastic, awesome, amazing! πŸš€πŸŒ• BUT sometimes demotivating because there are not as many resources as e.g. JavaScript out there.

So sometimes you are just so fed up that you want to quit but you remember yourself that you have started your mission to contribute to the blockchain world because it means something deep for you, even if currently the Resistance 😈 tells you the opposite (aaahh dear Resistance I love as much as I hate you 🀯).

Enough chit-chat! Let’s dive into techi side πŸ€“, my dear unicorns πŸ¦„

If you did not know, Angular creates a virtual DOM. That means you can not have direct access to every window objects.
I am quite sure you know what I mean if you are struggling with window.ethereum.

Solution - Create a dedicated service, like WinRefService below:

import { Injectable } from '@angular/core';const w = () => {
return window;
};
@Injectable()
export class WinRefService {
get window(): any {
return w();
}
}

Then import WinRefService to your app.module.ts and add it in providers array:

import { WinRefService } from 'services/win-ref.service';@NgModule({
declarations: [...],
imports: [...],
providers: [WinRefService],
})

Then wherever you need to inject the window.ethereum object passes it into your component’s constructor:

import { WinRefService } from 'services/win-ref.service';constructor(private winRef: WinRefService) {
this.ethereum = winRef.window.ethereum;
}

And that’s it! Now you can use window.ethereum in your app ✌ I hope this was helpful and I spare you the needed to go to Arkham πŸ˜‚

PS: Comment if you have any question left and share to help other people πŸ€—

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Blocks Creatorz
Blocks Creatorz

Written by Blocks Creatorz

Etherian unicorn πŸ¦„ sharing his knowledge, inspiration & energy πŸ”₯ Money is a powerful malleable universal energy πŸ—½

Responses (3)

Write a response