setTimeout函数中的错误有角度

时间:2018-06-06 03:04:58

标签: angular typescript

我是棱角分明的新人,我不明白为什么我会收到这个错误。我只是使用@angular/cli命令创建了一个新项目:

npm install -g @ angular / cli
ng new tutorial

我修改了component.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.

我做错了什么或问题是什么?

1 个答案:

答案 0 :(得分:2)

在angular中,不要直接在类中公开可执行代码,只需用函数或构造函数包装它。如果您希望在创建组件时执行代码,建议在OnInit生命挂钩中编写它。

见下面的代码示例:

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);
  }
}