在Angular 7中,如果你想在嵌套的函数中使用相同的变量,你可以使用箭头函数来解决这个问题。箭头函数继承了父函数的上下文,因此可以访问父函数的变量。
以下是一个示例代码:
export class AppComponent implements OnInit {
ngOnInit() {
let outerVariable = 10;
const nestedFunction = () => {
console.log(outerVariable); // 可以访问父函数的变量
};
nestedFunction();
}
}
在上面的例子中,我们在ngOnInit
函数中定义了一个变量outerVariable
并赋值为10。然后,我们定义了一个嵌套函数nestedFunction
,它使用箭头函数来访问outerVariable
变量。在调用nestedFunction
时,它会打印出outerVariable
的值。
这样就可以在Angular 7中的嵌套函数中使用相同的变量了。