如何在app.component.ts中访问index.html声明的全局变量
在Angular组件中获取index.html声明的全局变量
要在Angular的app.component.ts中获取index.html里声明的全局变量test,需要解决TypeScript的类型检查问题,以下是两种可行方案:
方案一:声明全局变量类型
在组件文件顶部添加全局变量的类型声明,让TypeScript识别该变量:
import { Component } from '@angular/core'; // 声明全局变量test的类型 declare var test: string; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { name = 'Angular 6'; constructor() { console.log(test); // 现在可正常访问全局变量test } }
方案二:通过window对象访问
用var声明的全局变量会挂载到浏览器的window对象上,可通过window获取该变量,同时处理TypeScript的类型校验:
import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { name = 'Angular 6'; constructor() { // 方式1:临时断言window为any类型 console.log((window as any).test); // 方式2:扩展Window接口(类型更安全,推荐) console.log(window.test); } } // 扩展Window接口,添加test属性的类型声明 declare global { interface Window { test: string; } }
补充说明
- 方案一适合仅在单个组件中使用该全局变量的场景
- 方案二更适合多组件需要访问该变量的场景,扩展接口后能获得类型提示,避免类型错误
内容的提问来源于stack exchange,提问作者EMahan K
相关产品推荐
相关产品推荐

