Reputation: 45
I am following a lesson about Angular in course on Udemy and in console I have this error
Uncaught TypeError: Cannot read properties of undefined (reading 'dispatchEvent') at :2:27
this is the code from the app component
import { Component, OnInit } from '@angular/core';
declare global {
interface Document {
monetization?:any;
}
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'web-monetization';
monetized=false;
ngOnInit() {
if (document.monetization){
document.monetization.addEventListener('monetizationstart', ()=> {
this.monetized=true;
});
}
}
pay() {
const event =new Event('monetizationstart');
document.monetization.dispatchEvent(event);
}
}
<section class="section">
<div class="container">
<h1 class="title">Some coding tutorial <button class="button is-link" (click)="pay()">Simulate payment</button></h1>
<div class="box">
<h2 class="subtitle is-2">
The first example
</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius metus quis dapibus lacinia. Proin faucibus faucibus nunc, non eleifend metus rutrum quis. Nullam molestie turpis id eros vulputate eleifend.
</p>
<code *ngIf="monetized" class="is-block">
const text= 'Here is text for the first example'; console.log(text);
</code>
<div *ngIf="!monetized" class="notification">
You Need Monetization to see the code
</div>
</div>
<div class="box">
<h2 class="subtitle is-2">
The second part
</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius metus quis dapibus lacinia. Proin faucibus faucibus nunc, non eleifend metus rutrum quis. Nullam molestie turpis id eros vulputate eleifend.
</p>
<code *ngIf="monetized" class="is-block">
const text= 'Here is text for the first example'; console.log(text);
</code>
<div *ngIf="!monetized" class="notification">
You Need Monetization to see the code
</div>
</div>
</div>
</section>
I am sure to have copied the rigth instruction so I don't know why I see the error
Upvotes: 0
Views: 487
Reputation: 10979
In pay method you don't have a check if monetization is available like you have in ngOnInit. In your browser monetization is undefined. See these states here :-
https://webmonetization.org/docs/api/#states
You can add a pollyfill :- https://www.npmjs.com/package/web-monetization-polyfill
Upvotes: 1