Angular: Strugguling with window.ethereum? ππ€¬
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 π€