0

I execute requests to the server and add them to the array of objects in the service:

async auth(login: string, password: string) {
    let data = this.ApiService.autorization(login, password);
    data = (isNullOrUndefined(await data)) ? [] : await data;
    this.ApiService.cars = data['cars'];

    for (let i = 0; i < this.ApiService.cars.length; i++) {
        let car = this.ApiService.cars[i];
        this.http.get('http://get/example/').subscribe((data) => {
            this.ApiService.carsPosition.push(data[0]);
        });
    }
  console.log(this.ApiService.carsPosition)
  console.log('lenght: ' + this.ApiService.carsPosition.length)
}

The console displays the following data: enter image description here

The data is received, but their length is zero. And I can’t use them. What to do?

Optimus
  • 111
  • 8
  • 2
    You should `await` the `this.http.get('http://get/example/)` call, not subscribe an asynchronous callback to it! – Bergi Mar 24 '20 at 21:42
  • 1
    It's an `Observable` btw – Guerric P Mar 24 '20 at 21:42
  • Probably you can't await the data twice, but that's not the reason – Chayim Friedman Mar 24 '20 at 21:43
  • 1
    Are you sure, because the logged array seems to have the correct length. There probably is a problem somewhere else. – Angshu31 Mar 24 '20 at 21:45
  • How can this structure be organized? – Optimus Mar 24 '20 at 21:51
  • I need all the parameters in the loop to be received and written to the array – Optimus Mar 24 '20 at 21:51
  • @ChayimFriedman You can `await` a promise as often as you want, it will always have the same result. (Admittedly, it would still make more sense to just write `let data = await this.ApiService.autorization(login, password);`) – Bergi Mar 24 '20 at 22:00
  • @LearnforFun The [expansion shown in the console screenshot happened after the data was loaded](https://stackoverflow.com/q/4057440/1048572), but that doesn't mean it's immediately available after the requests were started. – Bergi Mar 24 '20 at 22:01
  • @Bergi What are you trying to say? I merely pointed out that the logged array (of objects) had the correct length. – Angshu31 Mar 24 '20 at 22:05
  • @LearnforFun I'm saying that it has the correct (expected) contents *at the wrong time*. No, this is not a problem elsewhere, it's a problem right in the posted code. As you can see in the first line of that screenshot, the array (`[]`) is empty when it gets logged. – Bergi Mar 24 '20 at 22:07

0 Answers0