【问题标题】:Why .map() produces two different output?为什么 .map() 会产生两个不同的输出?
【发布时间】:2017-04-30 04:33:07
【问题描述】:

为什么 .map(() => x + 3) 与 .map((x) => x +3) 会产生两种不同的结果?

参见下面的代码 sn-p。我有以下代码 app.component.ts

obs = Observable.of(1, 2, 3, 4);

ngOnInit() {
    this.usingMapToMakeInnerObservable();
}

usingMapToMakeInnerObservable() {
    this.obs
        .map(x => Observable.timer(500).map(() => x + 3)) // A. Output 4, 5, 6, 7
        //.map(x => Observable.timer(500).map((x) => x + 3)) // B. Output 3, 3, 3, 3
        .subscribe(
            x => console.log(x),
            err => console.error(err),
            () => console.log('done completed')
        );
}

【问题讨论】:

  • 你也应该了解范围和闭包

标签: angular rxjs observable angular2-observables


【解决方案1】:

第一种情况

.map(x => //here x value can be `1, 2, 3, 4`
   Observable.timer(500).map(() => x + 3) // x will hold from last map
) 

在上面的代码中,首先 x 可以保存值1, 2, 3, 4,然后我们应用了Observable.timer。之后在.map x 将有当前的数组项。

在第二种情况下

.map(x =>  //here x value can be `1, 2, 3, 4`
   Observable.timer(500).map((x) => x + 3) //x here it has own x so
) 

在上面的代码中,第一个映射 x 值可以保存 1, 2, 3, 4 值。当我们声明 xtimer Observable 时。现在x 将不再是父映射的x 值。那么你一定是为什么它不断Output: 3,3,3,3。原因是当我们不向timer(Observable) 提及任何其他参数时,它每次都会返回0

【讨论】:

    猜你喜欢
    • 2022-12-05
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多