2017-09-13 138 views
0

这个问题应该很简单:我想将每个查询的状态推送到一个名为currentValues的数组中。 不幸的是,currentValues阵列仍然无人居住(校验值的输出是0vs2。我缺少什么吗?阵列推送不能正常工作

@Input() public wantedValue: string[]; 
    @Input() public querySensor: string[]; 
    @Input() public slideId: number; 
    @Output() wantedStateAccievedEvent: EventEmitter<any> = new EventEmitter<any>(); 
    public currentValues: string[] = []; 

    initItems() { 
    for (let sensor of this.querySensor) { 
     console.log("Sensor: " + sensor); 
     this.itemService.getMockItemState(sensor).subscribe(
     status => { this.currentValues.push((status)); }); 
    } 
    this.checkValues(); 
    } 

    checkValues(): void { 
    console.log("Called checkValues" + this.currentValues.length + "vs " + this.wantedValue.length); 
    let i = 0; 
    let allSatisfied: boolean; 
    for (let value of this.currentValues) { 
     console.log("Wert: " + value + '\n'); 
     if (this.wantedValue[i] !== value) { 
     allSatisfied = false; 
     } 
     i++; 
    } 
    if (allSatisfied === true) { 
     this.wantedStateAccievedEvent.emit({slideId: this.slideId, stateAccieved: true }); 
    } 
+0

的可能的复制[2角 - 直接从Observable返回数据](https://stackoverflow.com/questions/37867020/angular-2-return-data-directly-from-an-observable) – jonrsharpe

+0

你是否检查过“status”的值?如果添加这个,输出是什么:'console.log(status');'? – mok

+0

嗨,状态总是有一个值 - 整个事情使用数组,在更改wantedVaule和querySensor到数组后,问题出现 – jibjapda

回答

0

你订阅异步事件与this.itemService.getMockItemState(sensor).subscribe。所以这是可能的,当你调用this.checkValues()是不是已经触发事件

尽量推迟this.checkValues()用于填充秒或移动认购函数内部调用:

this.itemService.getMockItemState(sensor) 
    .subscribe(status => { 
    this.currentValues.push(status); 
    this.checkValues(); 
    }); 
+0

嗨,感谢您的回复 - 此作品,我已将代码更改为: 这是一个建议,但现在这个阵列变得非常庞大!即使有 'for(让我在this.querySensor){ console.log(“Sensor:”+ this.querySensor [i]); this.itemService.getMockItemState(this.querySensor [i])。subscribe( status => { this.currentValues [i] = status; }); this.checkValues(); } }' 阵列变得更大 - 我的莫服务: 'getMockItemState(项目:字符串):可观察 { 返回Observable.interval(500).MAP(()=> 'OPEN'); }' – jibjapda

+0

它最终以这种方式完成工作 - 谢谢你的帮助 – jibjapda