2017-09-13 127 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