Issue
Can you explain why the constructor uses (window as any)?
AfterContentInit, Component, ElementRef, NgZone, ViewChild,
} from '@angular/core';
import { AppState } from 'app/model/app-state';
import { User } from '../model/type';
@Component({
selector: 'app-telegram-login-widget',
template: `
<div #script>
<ng-content></ng-content>
</div>
`,
})
export class TelegramLoginWidgetComponent implements AfterContentInit {
@ViewChild('script', { static: true }) script!: ElementRef;
Can you explain why the constructor uses (window as any)?
constructor(private ngZone: NgZone, private appstate: AppState) {
(window as any).onTelegramAuth = (user: User) => {
this.ngZone.run(() => {
this.appstate.setUser(user);
console.log('hello');
});
};
}
convertToScript() {
const element = this.script.nativeElement;
const script = document.createElement('script');
script.src = 'https://telegram.org/js/telegram-widget.js?5';
script.setAttribute('data-telegram-login', 'rennat_bot');
script.setAttribute('data-size', 'large');
// Callback function in global scope
script.setAttribute('data-onauth', 'onTelegramAuth(user)');
script.setAttribute('data-request-access', 'write');
element.parentElement.replaceChild(script, element);
}
ngAfterContentInit(): void {
this.convertToScript();
}
}
I wanted to implement authorization via Telegram Login Widget and found this code, but I don't understand why I need to use (window as any).
Solution
TypeScript enforces strict types and does not recognize onTelegramAuth as part of window. Casting window to any bypasses TypeScript’s type checking, allowing the addition of non-standard properties or methods.
Update: you can extend the Window interface with your custom onTelegramAuth method.
Here’s how you can do it:
First, you should declare a custom interface that extends the global Window interface, adding your onTelegramAuth method. Use this custom interface to assert the type of the global window object when assigning the onTelegramAuth method
interface CustomWindow extends Window {
onTelegramAuth?: (user: User) => void;
}
@Component({
// metadata
})
export class TelegramLoginWidgetComponent implements AfterContentInit {
@ViewChild('script', { static: true }) script!: ElementRef;
constructor(private ngZone: NgZone, private appState: AppState) {
// Assign the method to the window object using the custom interface
const customWindow: CustomWindow = window;
customWindow.onTelegramAuth = (user: User) => {
this.ngZone.run(() => {
this.appState.setUser(user);
console.log('User logged in via Telegram');
});
};
}
}
Answered By - berkobienb
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.