我想使用 TypeScript
创建一个简单的 Angular2
应用程序。看起来,很简单,但我无法实现我想要的。
我想在模板中显示属性值。我想在 1 秒后使用 setTimeout 更新它。
Plunkr 代码在这里:Code on Plunkr
我写的是这里:
import {Component} from 'angular2/core';
interface Hero {
id: number;
name: string;
}
@Component({
selector: 'my-app',
template:`<h1>Number Increment</h1><p>{{n}}</p>`
})
export class AppComponent {
public n : number = 1;
setTimeout(function() {
n = n + 10;
}, 1000);
}
当我使用此代码时出现以下错误:
Uncaught SyntaxError: Unexpected token ;
为什么我无法访问 n
,它与我们过去在 JavaScript 中的作用域相同。如果我没记错的话,我们也可以在 TypeScript 中使用纯 JavaScript。
我什至尝试过
export class AppComponent {
public n : number = 1;
console.log(n);
}
但我无法在控制台中看到 n
的值。
当我尝试过
export class AppComponent {
public n : number = 1;
console.log(this);
}
我收到与上述相同的错误。为什么我们不能在这个地方访问它。我想,this
指的是 JavaScript 中的当前上下文。
最佳答案
这不是有效的 TypeScript 代码。您不能在类的主体中调用方法。
// INVALID CODE
export class AppComponent {
public n: number = 1;
setTimeout(function() {
n = n + 10;
}, 1000);
}
而是将 setTimeout
调用移至类的 constructor
。此外,使用箭头函数 =>
可以访问 this
。
export class AppComponent {
public n: number = 1;
constructor() {
setTimeout(() => {
this.n = this.n + 10;
}, 1000);
}
}
在 TypeScript 中,您只能通过 this
来引用类的属性或方法。这就是箭头函数 =>
很重要的原因。
关于typescript - Angular2 - typescript : Increment a number after timeout in AppComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34529557/