Angular 角度传感器中的setTimeout函数出错
我是angular的新手,我不明白为什么会出现这个错误。我只是使用Angular 角度传感器中的setTimeout函数出错,angular,typescript,Angular,Typescript,我是angular的新手,我不明白为什么会出现这个错误。我只是使用@angular/cli命令创建了一个新项目: npm install -g @ angular / cli ng new tutorial 我修改了组件.ts文件 export class AppComponent { title = 'app'; myselect:any; test:any= [{"id": "1", "nombre":"pedro" },{"id": "2", "nombre":"yeison" }
@angular/cli
命令创建了一个新项目:
npm install -g @ angular / cli
ng new tutorial
我修改了组件.ts
文件
export class AppComponent {
title = 'app';
myselect:any;
test:any= [{"id": "1", "nombre":"pedro" },{"id": "2", "nombre":"yeison" }];
setTimeout(function(){ alert("Hello"); }, 3000);
}
在setTimeout
行中,我得到了这个错误
ERROR in src/app/app.component.ts(15,14): error TS1138: Parameter
declaration expected. src/app/app.component.ts(15,42): error TS1068:
Unexpected token. A constructor, method, accessor, or property was expected.
src/app/app.component.ts(15,48): error TS1005: ';' expected.
我做错了什么或者问题出在哪里?从角度看,不要直接在类中公开可执行代码,只需用函数或构造函数将其包装。若您希望在创建组件时执行代码,建议在OnInit life hook中编写 请参见下面的代码示例:
export class AppComponent implements OnInit {
title = 'app';
myselect:any;
test:any= [{"id": "1", "nombre":"pedro" },{"id": "2", "nombre":"yeison" }];
ngOnInit() {
// by calling function here, you function will be executed when angular init your component
this.timeoutFun();
}
// wrap code in a function
timeoutFun() {
setTimeout(function(){ alert("Hello"); }, 3000);
}
}
在angular中,不要直接在类中公开可执行代码,只需使用函数或构造函数将其包装。如果您希望在创建组件时执行代码,建议将其写入
OnInit
life hook@Pengyy,如果我将myfunction(){setTimeout…};myfunction()可以工作吗?你是什么意思?很难在评论中解释,我在下面的回答中给出了一个例子。