Angular 5视图超时后不更新

问题描述 投票:10回答:4

我在Angular 5中设置了一段时间后隐藏元素的超时:

this.showElement = true;
setTimeout(function () {
  console.log('hide');
  this.showElement = false;
}, 2000);

但是,这不会更新视图。 console.log给了我一个输出,所以超时肯定有效。

我发现在Angularjs你需要调用$apply来开始一个摘要,所以我猜我只需要找到Angular 5等效的方法。

javascript angular asynchronous
4个回答
25
投票

我认为setTimeout回调会将范围丢失到变量“showElement”。

this.showElement = true; // this - is in component object context
setTimeout(function () {
   console.log('hide');
   this.showElement = false; // here... this has different context
}, 2000);

你应该使用箭头功能:

this.showElement = true;
setTimeout(() => {
  console.log('hide');
  this.showElement = false;
}, 2000);

或者使用bind

this.showElement = true;
setTimeout(function() {
  console.log('hide');
  this.showElement = false;
}.bind(this), 2000);

将适当的上下文传递给setTimeout回调函数。


3
投票

当你使用函数样式“this”引用不起作用时,请执行以下操作,您的示例将正常工作

this.showElement = true;
setTimeout(() => {
    console.log('hide');
    this.showElement = false;
}, 2000);

3
投票

更新:更正的答案。

正如其他人正确回答的那样,没有反映出这些变化的原因是因为对this参考的错误引用。

请注意,使用function() { ... }表示法时,对this的引用是函数本身的上下文。所以

myFunction() {
    this.showElement = true;
    setTimeout(function() {
      console.log(this.showElement); // Will result in undefined;
      this.showElement = false; // Here, this, reference to context of the function wrapper
    }, 2000);
}

将上面的内容更改为ES6箭头表示法,将this引用的上下文更改为父上下文。所以

myFunction() {
    this.showElement = true;
    setTimeout(() => {
      console.log(this.showElement); // Will result in true;
      this.showElement = false; // Here, value is updated
    }, 2000);
}

阅读更多关于lexical this here的信息。


0
投票

我在Angular 7应用程序中遇到了同样的问题。我不得不在按钮中更改标题和图标的来源:

<button class="btn btn--outline-red text-uppercase font-weight-normal product-action-btn mt-3"
              (click)="addToCart()">
              {{addToCartProps.title}}
              <img style="width:15px; height:15px;" [src]="addToCartProps.src">
            </button>

.......

  addToCartProps = { title: 'Add to Cart', src: '' }

  addToCart() {

    this.addToCartProps.title = 'Adding';
    this.addToCartProps.src = 'assets/images/preloader-white.svg';

    setTimeout(() => {
      this.addToCartProps.title = 'Added';
      this.addToCartProps.src = 'assets/images/checked-icon-white.svg';
      this.cd.markForCheck();
      console.log('timeout 1 ', this.addToCartProps);
    }, 1000);

    setTimeout(() => {
      this.addToCartProps.title = 'Add to cart';
      this.addToCartProps.src = '';
      this.cd.markForCheck();
      console.log('timeout 2 ', this.addToCartProps);
    }, 1500);

  }

在超时函数中添加this.cd.markForCheck()解决了我的问题。

此前,Angular2, view not updating after variable changes in settimeout的@artemisian也对此进行了评论

© www.soinside.com 2019 - 2024. All rights reserved.