Angular2 – TypeScript:在AppComponent中超时后增加一个数字

前端之家收集整理的这篇文章主要介绍了Angular2 – TypeScript:在AppComponent中超时后增加一个数字前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用TypeScript创建一个简单的Angular2应用程序.似乎很简单,但我无法实现我想要的.

我想在模板中显示属性值.而且我想使用setTimeout更新1秒后.

Plunkr Code在这里:Code on Plunkr

我写的是这里:

  1. import {Component} from 'angular2/core';
  2.  
  3. interface Hero {
  4. id: number;
  5. name: string;
  6. }
  7.  
  8. @Component({
  9. selector: 'my-app',template:`<h1>Number Increment</h1><p>{{n}}</p>`
  10. })
  11. export class AppComponent {
  12. public n : number = 1;
  13. setTimeout(function() {
  14. n = n + 10;
  15. },1000);
  16. }

当我使用这个代码我得到以下错误

  1. Uncaught SyntaxError: Unexpected token ;

为什么我无法访问n,这与我们以前在JavaScript中所做的一样.如果我没有错,我们也可以在TypeScript中使用纯JavaScript.

我甚至试过

  1. export class AppComponent {
  2. public n : number = 1;
  3. console.log(n);
  4. }

但是我无法在控制台中看到n的值.

当我试过

  1. export class AppComponent {
  2. public n : number = 1;
  3. console.log(this);
  4. }

我得到与上述相同的错误.为什么我们不能在这个地方访问这个.我猜,这是指JavaScript中的当前上下文.

提前致谢.

这是无效的脚本代码.您不能在类的正文中进行方法调用.
  1. export class AppComponent {
  2. public n: number = 1;
  3. setTimeout(function() {
  4. n = n + 10;
  5. },1000);
  6. }

而是在类的构造函数中移动setTimeout调用.

  1. export class AppComponent {
  2. public n: number = 1;
  3.  
  4. constructor() {
  5. setTimeout(() => {
  6. this.n = this.n + 10;
  7. },1000);
  8. }
  9.  
  10. }

同样在TypeScript中,您也可以通过这种方式引用类属性方法.

猜你在找的Angularjs相关文章