【发布时间】: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