我基于 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]
           })

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

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

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

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

干杯

最佳答案

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

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

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

关于angular - angular2 如何检测有状态管道的变化?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34713178/

10-14 16:41
查看更多