【问题标题】:How does angular2 detect the changes in a stateful pipe?angular2 如何检测有状态管道的变化?
【发布时间】:2016-04-15 06:26:56
【问题描述】:

我基于Angular.io tutorial on pipes创建了一个简单的有状态管道:

@Pipe({
    name: 'fetch',
    pure: false
})

class FetchJsonPipe  implements PipeTransform{
    private fetchedValue = 'waiting';
    private fetchedValue2 = 'waiting2';

    transform(value:string, args:string[]):any {
        setTimeout(() => {
            this.fetchedValue = 'done';
            this.fetchedValue2 = 'done2';
        }, 3000);
        return this.fetchedValue2;
    }
}

@Component({ selector: 'sd-splash'
           , template: 'hello ng2 {{ "5" | fetch }}'
           , pipes: [FetchJsonPipe]
           })

我的问题是,我立即从#transform 返回this.fetchedValue。 因为它只是一个字符串,所以它按值返回。后来,当超时 完成后,我只需将值 'done' 分配给一个属性(这也是 私人)。

Angular2 怎么知道初始结果 'waiting' 不是最终结果?如何 它知道更新后的值可以通过#fetchedValue 获得吗? Promise 完全没有暴露,Angular2 也没有名字的信息 我存储结果的字段。

它唯一的线索是pure == false,我猜它指示它 观察实例的变化。但我不明白它是如何提供信息的 观看哪个字段

但它有效!我也不知道为什么。

干杯

【问题讨论】:

    标签: angular typescript frontend


    【解决方案1】:

    Angular 猴子使用名为 Zone.js 的库修补浏览器事件(包括 setTimeout())。当事件发生时,AngularJS 会触发变更检测。

    使用有状态管道,AngularJS 将在每​​个事件上重新评估管道,因为即使输入相同,管道结果也可能发生变化。

    对于纯管道,AngularJS 将触发更改检测并仅在输入之一发生更改时重新评估管道(即数据进入,或 args)。

    【讨论】:

    • 谢谢!它怎么知道它应该为新值寻找 fetchedValue 属性?
    • 在更改检测期间,angularjs 检查 all 绑定的更改。
    • 我更新了代码示例以使用#fetchedValue#fetchedValue2。如果我返回this.fetchedValue2,它会在超时触发时使用#fetchedValue2 正确更新值。我的问题是,它怎么知道应该使用#fetchedValue2 而不是#fetchedValue 更新视图?转换函数最初只返回'waiting',没有指示它在哪个属性中。该属性也没有绑定到任何地方。
    • 管道的结果和视图对结果的呈现之间存在隐式绑定。超时事件触发后,AngularJS 将重新评估管道并更新所有绑定。
    【解决方案2】:

    要理解这一点,我认为最好看一下Zone.js 上的演讲。 基本上 Angular 在 setTimeout 调用完成后(如果需要)使用名为 zone 的库来执行 $rootScope 摘要

    不仅如此,即使在任何承诺解决之后,也会触发摘要循环。

    这正是因为它不知道哪些属性可能发生了变化,所以它会脏检查整个应用程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      相关资源
      最近更新 更多