-1

I have such a function;

getList() {
    this.http.get(this.rootURL )
    .toPromise().then(res => { this.mimeList = res as Mime[];
                               this.arrayLenght = this.mimeList.length;
    });
    return this.arrayLenght;
  }

In this function, I want to return the lenght of the mimeList array. The variable arrayLength is used to store the length value and declared in the body of the class like this;

export class MimeService {
         .
         .
         .
         .
  arrayLenght = 0;
         .
         .
         .
         .
         .
         .
}

When I place a console.log statement inside of the this.http.get(this.rootURL ).toPromise().then body, it prints me the real length of the array. So it means, there is no problem for retrieving the length of this array. However, in the other class where I am calling the getList() function;

export class AssetListComponent implements OnInit {
             .
             .
             .
             .
             .
             .
ngOnInit() {
  this.service.getList();
  this.serviceCountry.getList();
  this.databaseLength = this.serviceMime.getList();
}
             .
             .
             .
             .
             .
             .
}

The returned value is "0" instead of the real length of the array. I can see this when I run console.log(this.databaseLength).

Where I am wrong? I am very new in Typescript and most probably the answer of this question is very easy. Thanks in advance.

Ozan Yurtsever
  • 1,274
  • 8
  • 32

1 Answers1

2
async getList() {
    const res = await this.http.get(this.rootURL ).toPromise();
    this.mimeList = await res as Mime[];
    this.arrayLenght = this.mimeList.length;
    return this.arrayLenght;
}

Change your getList() function like this. You should wait until your promise gets resolved. In your other class add the await keyword before calling getList();

this.databaseLength = await this.serviceMime.getList();
Thivagar
  • 590
  • 6
  • 13