0

This problem should be quite simple: I want to push the status of each query into an array called currentValues. Unfortunately, the currentValues-array remains unpopulated (the output of check values is 0vs2. What am I missing here?

 @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 });
    }
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
jibjapda
  • 87
  • 2
  • 2
  • 9
  • Possible duplicate of [Angular 2 - Return data directly from an Observable](https://stackoverflow.com/questions/37867020/angular-2-return-data-directly-from-an-observable) – jonrsharpe Sep 13 '17 at 22:48
  • Have you checked what is the value of the `status`? What is the output if you add this: `console.log(status');`? – Mohsen Kamrani Sep 13 '17 at 22:50
  • Hi, the status always has a value - the whole thing worked with out using arrays, after changing wantedVaule and querySensor to arrays the issue appeared – jibjapda Sep 14 '17 at 05:53

1 Answers1

0

You're subscribing to an asynchronous event with this.itemService.getMockItemState(sensor).subscribe. So it's possible that when you call this.checkValues() the event wasn't triggered already.

Try postpone the this.checkValues() for a fill seconds or move the call inside the subscribe function:

this.itemService.getMockItemState(sensor)
  .subscribe(status => {
    this.currentValues.push(status);
    this.checkValues();
  });
  • Hi thank you for the response - this works, I have changed the code to: to you're suggestion, but now the array just grows huge! even with `for ( let i in this.querySensor ) { console.log("Sensor: " + this.querySensor[i]); this.itemService.getMockItemState(this.querySensor[i]).subscribe( status => { this.currentValues[i] = status; }); this.checkValues(); } } ` The array becomes larger - my mok service: `getMockItemState(item: String): Observable { return Observable.interval(500).map(() => 'OPEN'); }` – jibjapda Sep 14 '17 at 05:49
  • It acutually worked exactly this way in the end - thank you for you're help – jibjapda Sep 14 '17 at 06:13