【问题标题】:Angular 2+ setTimeout()Angular 2+ setTimeout()
【发布时间】:2017-08-26 17:06:13
【问题描述】:

我是 Angular 2 的新手。我想在 app.component.ts 中使用 setTimeout()。我尝试引用许多其他帖子,但对我没有任何帮助。

下面是我尝试做的代码。

app.component.ts

catchError() {
    if (navigator.onLine) {
        console.log("connected");
        this.displayNetworkError = false;
    } else {
        console.log("Disconnected");
        this.displayNetworkError = true;
    }
};

internetConnection() {
    setTimeout(this.catchError(), 2000);
};

请帮我举几个例子。

【问题讨论】:

  • setTimeout(() => this.catchError(), 2000);你传递的是 callable 的东西,而不是 callable 的东西。

标签: angular typescript settimeout


【解决方案1】:

setTimeout 需要一个函数和一个以毫秒为单位的持续时间。通常在 javascript 中你会传递一个像 setTimeout(function() {}, 1000) 这样的函数。但是在 typescript 中你可以使用 lambda 表达式,比如 setTimeout(() => {}, 1000)

【讨论】:

  • 你能帮我举个例子吗
  • 你所说的 lambda 被称为“箭头函数”,它们在新版本的纯 javascript 中可用,而不仅仅是 typescript。
  • 我正在尝试这个,但它只被调用一次
  • ngOnInit() { setTimeout(() => {this.internetConnection();}, 1000); } internetConnection(){ if(navigator.onLine){ console.log("connected"); } else{ console.log("断开连接"); } }
【解决方案2】:

你在编写this.catchError()时正在执行函数catchError

setTimeout 的第一个参数需要是一个函数 所以只需使用 this.catchError 而不是 this.catchError()

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多