我正在尝试在正在开发的Angular网页的TypeScript程序中执行一些if / else语句。这是一个可重现的案例:
export class AppComponent {
x: number = 0;
output: number = 0;
if (this.x < 0.5){
this.output = 1;
}
else if ((this.x >= 0.5) && (this.x < 1.0)){
this.output = 2;
}
else {
this.output = 3;
}
}
在我看来,这与我阅读的有关TypeScript语法的教程相匹配,但是显然有些错误。
在Visual Studio代码编辑器中,它显示:
而且,当我去运行代码时,调试控制台会说:
[WDS] Errors while compiling. Reload prevented.
(webpack)-dev-server/client:162
app.component.ts(10,11): error TS1005: ',' expected.
app.component.ts(10,22): error TS1005: ',' expected.
app.component.ts(10,24): error TS1003: Identifier expected.
app.component.ts(13,3): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
答案 0 :(得分:2)
您的代码不在函数中。
不确定要达到的目标。
例如,您可以将代码放入构造函数中:
export class AppComponent {
x = 0; // note that the type is inferred therefore the type declaration is not necessary
output = 0;
constructor() {
if (this.x < 0.5){
this.output = 1;
}
else if ((this.x >= 0.5) && (this.x < 1.0)){
this.output = 2;
}
else {
this.output = 3;
}
}
}
答案 1 :(得分:1)
您不能只在类中间抛出一些语句并期望它起作用。您必须创建类方法或将语句添加到类的构造函数或角度生命周期挂钩。
IE。
constructor() {
if (this.x < 0.5){
this.output = 1;
}
else if ((this.x >= 0.5) && (this.x < 1.0)){
this.output = 2;
}
else {
this.output = 3;
}
}
或myFunct(){...代码},然后从某个地方调用this.myFunct()。