【问题标题】:Call a function after data is rendered in the template: Angular2在模板中渲染数据后调用函数:Angular2
【发布时间】:2017-08-03 21:04:57
【问题描述】:

我正在订阅一个正在调用 API 的方法。在订阅正文中,我将接收到的数据分配(第一次分配并第二次修改对象)以下列方式分配给对象:

this.serviceObj.getData()
  .subscribe(
  data => {
    this.DataObj = {
      ..... some content .....
    }
    this.anotherFunction();
  },
  error => {
    console.log('error');
  },
  );

在订阅正文中,一旦我收到数据,我会将其分配给“DataObj”,并且在 DataObj 获得新数据后,它会在 UI 中呈现。我希望在为“dataObj”分配新数据并在 UI 中呈现之后执行“anotherFunction()”。但看起来数据已成功分配,但在新数据成功呈现在 UI 中之前,正在执行“anotherFunction()”。

我尝试使用:

ngAfterViewChecked() {
  this.anotherFunction();
}

如果我将“anotherFunction()”放在 ngAfterViewChecked() 中,则会在视图更改后执行,但即使模板中有微小更改,它也会继续执行,但我只希望它在“DataObj”已更改。

有什么建议可以让我有效地完成这项工作吗? (不会让 ngAfterViewChecked() 经常执行)。

【问题讨论】:

  • 你试过ngOnChanges吗?
  • 我试过这样做,@JasonSpradlin。但是阅读 Angular 关于 ngOnChanges 的文档时,它说“当指令的任何数据绑定属性发生更改时调用的生命周期钩子。”所以当我收到数据时,ngOnChanges 没有被执行。

标签: angular


【解决方案1】:

唯一想到的是基于“信号量”的方法。将标志 dataReceived 设置为 false。在 .subscribe 中,将其设置为 true。然后在ngAfterViewChecked() 中仅在dataReceived 为真时运行代码。

ngAfterViewChecked() {
  if (this.dataRetrieved) {
     this.anotherFunction();
     this.dataRetrieved = false;
  }
}

我不喜欢“基于标志”的方法。但这是唯一想到解决这个问题的事情。也许其他人有更好的解决方案?

【讨论】:

  • 我现在正在这样做。但正如你所说,这不是最好的方法。但是感谢您的回答:)
【解决方案2】:

管道呢?

它在渲染之前运行,你可以调用anotherFunction

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'anotherFunction'})
export class AnotherFunctionPipe implements PipeTransform {

  transform(value: any): number {

    anotherFunction();

    return value;
  }

  anotherFunction() {
     // do something  
  }

}

用法是这样的

<div> {{ DataObj | anotherFunction }} </div>

【讨论】:

    猜你喜欢
    • 2014-10-10
    • 1970-01-01
    • 2014-12-08
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2020-03-11
    • 1970-01-01
    相关资源
    最近更新 更多