加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:41:24 所属栏目:安全 来源:网络整理
导读:我想使用TypeScript创建一个简单的Angular2应用程序.似乎很简单,但我无法实现我想要的. 我想在模板中显示属性值.而且我想使用setTimeout更新1秒后. Plunkr Code在这里:Code on Plunkr 我写的是这里: import {Component} from 'angular2/core';interface He
我想使用TypeScript创建一个简单的Angular2应用程序.似乎很简单,但我无法实现我想要的.

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

Plunkr Code在这里: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);
}

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

提前致谢.

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

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

export class AppComponent {
  public n: number = 1;

  constructor() {
    setTimeout(() => {
      this.n = this.n + 10;
    },1000);
  }

}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读