在Angular 9中,要访问函数作用域之外的变量,可以通过以下几种方式实现:
function myFunction(externalVariable: any) {
// 在函数内部可以访问externalVariable
console.log(externalVariable);
}
const myVariable = 'Hello World';
myFunction(myVariable);
src
目录下的main.ts
文件中。例如:// main.ts
(window as any).myVariable = 'Hello World';
// 在其他组件或服务中访问myVariable
console.log((window as any).myVariable);
// my-data.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyDataService {
private externalVariable: any;
setExternalVariable(value: any) {
this.externalVariable = value;
}
getExternalVariable() {
return this.externalVariable;
}
}
// my-component.ts
import { Component } from '@angular/core';
import { MyDataService } from './my-data.service';
@Component({
selector: 'app-my-component',
template: `
<button (click)="logExternalVariable()">Log External Variable</button>
`
})
export class MyComponent {
constructor(private myDataService: MyDataService) {}
logExternalVariable() {
const externalVariable = this.myDataService.getExternalVariable();
console.log(externalVariable);
}
}
以上是在Angular 9中访问函数作用域之外的变量的几种方法。根据具体的需求和场景,选择适合的方式来实现。
领取专属 10元无门槛券
手把手带您无忧上云