2017-09-13 1 views
0

이 문제는 매우 간단합니다. 각 쿼리의 상태를 currentValues라는 배열로 푸시합니다. 는 불행하게도, currentValues ​​배열이 채워지지 않은 남아 (검사 값의 출력은 0vs2. 내가 여기에 놓친 거지 뭐? 당신은 this.itemService.getMockItemState(sensor).subscribe와 비동기 이벤트에 가입하고배열 푸시가 올바르게 작동하지 않습니다.

@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

안녕하세요, 상태가 항상 값을 가지고 있습니다 - 배열을 사용하여 배열을 사용하여 배열을 사용하여 배열을 사용하여 모든 작업을 수행했습니다. – jibjapda

답변

0

.이 가능 그래서 당신이 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 ( 상태 => { this.currentValues ​​[i] = 상태; }); this.checkValues ​​(); 은} 은}' 배열은 더 커진다 - 내 목동 서비스 : 'getMockItemState (항목 : 문자열) : 관찰 가능한 { 반환 Observable.interval (500) .MAP (() => 'OPEN'); }' – jibjapda

+0

끝 부분에서 정확히이 방법으로 정확하게 작동했습니다. 도움을 주셔서 감사합니다. – jibjapda

관련 문제