我开始编写 Angular 2 程序,但遇到了一个错误:
ts1206 装饰器在这里无效
@Component({ // ts1206 decorators are not valid here
selector: 'my-app',
moduleId: module.id,
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
更新:
我的 tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
我可以用它做什么?
装饰器必须直接位于导出类之前,例如:
@Component({
...
})
export class someComponent{}
这对于
@Pipe
@Directive
@Injectable
和 @NgModule
来说是一样的
当我在
@NgModule
装饰器之后使用角度路由和定义路线时,出现了这个错误。
我们需要在
@NgModule
装饰器之前定义路由或任何其他装饰器。
const appRoutes: Routes = [ // define this before @NgModule
{ path: '',
redirectTo: '/home',
pathMatch: 'full'
},
{ path: 'home', component: HomeComponent },
];
@NgModule({ // This Decorator should be just before an exported class
declarations: [
AppComponent,
HeaderComponent,
HomeComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- debugging purposes only
)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
以防有人因为 VSCode 的 IntelliSense 的奇怪错误而来到这里,该错误将某些装饰器标记为无效。
要解决此问题,请在工作区中创建文件
.vscode/settings.json
:
{
"js/ts.implicitProjectConfig.experimentalDecorators": true
}
在上面添加接口或其他声明
@component
。这将修复错误。