在 Angular 中从不同范围获取变量和调用函数
Fetching variables & calling functions from different scope in Angular
我在 ngOnInit() 中有一个本地函数 compulsiveFunction() ,它由我正在使用的库自动触发。我必须将它作为 ngOnInit 中的本地函数。
问题 - 我无法访问变量或调用在 angular 组件中声明的函数。
export class MyComponent implements OnInit {
message= "Hello";
OuterFunction(){
console.log("Outer Function called");
}
ngOnInit(): void {
console.log('msg0: ',this.message);
function compulsoryFunction() {
console.log('msg: ',this.message);
this.OuterFunction();
}
错误如下:
组件中定义的变量或函数不是默认public吗?
提前致谢!
您可以使用 arrow functions 更改 this
上下文。
export class MyComponent implements OnInit {
message = 'Hello';
OuterFunction() {
console.log('Outer Function called');
}
ngOnInit() {
console.log('msg0: ', this.message);
const compulsoryFunction = () => {
console.log('msg: ', this.message);
this.OuterFunction();
};
}
}
我在 ngOnInit() 中有一个本地函数 compulsiveFunction() ,它由我正在使用的库自动触发。我必须将它作为 ngOnInit 中的本地函数。
问题 - 我无法访问变量或调用在 angular 组件中声明的函数。
export class MyComponent implements OnInit {
message= "Hello";
OuterFunction(){
console.log("Outer Function called");
}
ngOnInit(): void {
console.log('msg0: ',this.message);
function compulsoryFunction() {
console.log('msg: ',this.message);
this.OuterFunction();
}
错误如下:
组件中定义的变量或函数不是默认public吗?
提前致谢!
您可以使用 arrow functions 更改 this
上下文。
export class MyComponent implements OnInit {
message = 'Hello';
OuterFunction() {
console.log('Outer Function called');
}
ngOnInit() {
console.log('msg0: ', this.message);
const compulsoryFunction = () => {
console.log('msg: ', this.message);
this.OuterFunction();
};
}
}