根据此处的讨论,我必须扩展窗口对象才能强类型 Intercom 的窗口功能。
最初的代码是这样的:
setCurrentRoute() {
if (
this.currentRoute.getValue().indexOf('website') > -1 ||
this.currentRoute.getValue().indexOf('builder') > -1
) {
(window as any).Intercom('update', {
hide_default_launcher: true,
});
} else {
(window as any).Intercom('update', {
hide_default_launcher: false,
});
}
localStorage.setItem('currentRoute', this.currentRoute.getValue());
}
Run Code Online (Sandbox Code Playgroud)
但当我尝试利用更多 Typescript 的类型安全功能时,它现在看起来像这样:
declare global {
interface Window {
Intercom(update: string, params: { hide_default_launcher: boolean }): void;
}
}
setCurrentRoute(): void {
if (this.currentRoute.getValue().indexOf('website') > -1 || this.currentRoute.getValue().indexOf('builder') > -1) {
this.window.Intercom('update', {
'hide_default_launcher': true
});
} else {
this.window.Intercom('update', {
'hide_default_launcher': false
});
}
localStorage.setItem('currentRoute', this.currentRoute.getValue());
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到以下错误消息:
ERROR TypeError: Cannot read property 'Intercom' of undefined
at RouterService.push../src/app/shared/services/router.service.ts.RouterService.setCurrentRoute
Run Code Online (Sandbox Code Playgroud)
我如何解决它?
Ben*_*ing 14
以下是我如何让打字稿和对讲机工作:
yarn add -D @types/intercom-webtsconfig.json{
"compileOnSave": false,
"compilerOptions": {
....,
"types": [...., "@types/intercom-web"]
}
}
Run Code Online (Sandbox Code Playgroud)
window.Intercom并且命名空间Intercom_将全局可用,例如:Intercom_.IntercomSettings我设法通过执行以下操作来修复它:
export interface RouterWindow extends Window {
Intercom(update: string, params: { hide_default_launcher: boolean }): void;
}
setCurrentRoute(): void {
if (this.currentRoute.getValue().indexOf('website') > -1 || this.currentRoute.getValue().indexOf('builder') > -1) {
(<RouterWindow>window).Intercom('update', {
'hide_default_launcher': true
});
} else {
(<RouterWindow>window).Intercom('update', {
'hide_default_launcher': false
});
}
localStorage.setItem('currentRoute', this.currentRoute.getValue());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2401 次 |
| 最近记录: |