typescript - Angular2 - typescript : Increment a number after timeout in AppComponent

标签 typescript angular

我想使用 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/

相关文章:

angular - 如何将 AngularFire2 身份验证作为可观察的?

javascript - 如何为 commonjs 和全局变量生成 TypeScript 定义?

javascript - 使用 javascript 的无限循环(Angular NgFor 和 http 请求)

javascript - 在 ES6/Typescript 中使用 _(下划线)变量和箭头函数

angular - 来自 ngrx/entity 的 SelectAll 没有选择任何东西

javascript - 类型 'Observable<LoginRequest>' 的参数不可分配给类型 'LoginRequest' 的参数

image - ionic 2 + Angular 2 : Images prepended with 'unsafe:' therefore not displaying even though they're fine

javascript - 括号中的点用于访问嵌套属性

typescript - 无法使用 web-assembly rust impl,因为 'Cannot access ' __wbindgen_throw' before initialization' 错误

派生类的 typescript 方法装饰器