【问题标题】:Angular2:how to use the observable to broadcast event within forEach?Angular2:如何使用 observable 在 forEach 中广播事件?
【发布时间】:2017-02-22 03:15:17
【问题描述】:

我发现当我在forEach中使用服务时,我发送给服务的参数成为循环的最后一个。

我认为应该是闭包导致了这个问题,所以我尝试使用匿名函数来解决它,但没有成功

在Component中传递obj

这个函数在ngOnInit中触发可能会导致问题

当我将此代码放入点击事件时,它工作正常

   for (var y = 0; y < this.model.data.length;y++) {
       if (this.model.data[i].to[x].id === this.model.data[y].id) {
           let obj = {
               selectedItem : this.model.data[i],
               item : this.model.data[y]
           };    
           (function(_obj,a) {
                console.log ('obje in component:');
                console.log (_obj.item.id)    //each obj over here is correct now

                a._drawLineService.drawLine(_obj);
                a._dragLineService.dragLine(_obj.item);
            })(obj,this)                                   
        }
   }

获取指令中的obj

this.subscription = this._drawLineService.drawLine$
   .subscribe(obj => {  
       console.log ('drawLine:')     
       console.log (obj.item.id) //each obj over here become the last one of array                                                                      
   });

我使用 observable 将事件和参数从组件传递到指令

我的服务

import {Injectable}      from '@angular/core'
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

@Injectable()
export class DrawLineService {
  private _drawLine = new BehaviorSubject<any>('');
  drawLine$ = this._drawLine.asObservable();
  drawLine(item) {
    this._drawLine.next(item);
  }
}

控制台结果:

如何解决?

【问题讨论】:

    标签: javascript angular foreach


    【解决方案1】:

    var obj=... 更改为let obj=...

    let 将变量定义为块作用域,而var 将变量定义为函数或全局作用域。

    实际上,您一直在用循环覆盖 obj 变量。

    【讨论】:

    猜你喜欢
    • 2018-02-13
    • 2015-10-20
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    相关资源
    最近更新 更多