Is there a way to ensure that my Angular functions are executed sequentially in the ngOnInit()
lifecycle hook? I attempted to use async, but it didn't work as expected...
nbPage()
getAllCommerces(page)
sort()
getCommerces(isFirstLoad, event)
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { GeolocationService } from '../services/geolocation.service';
@Component({
selector: 'app-commerces',
templateUrl: './commerces.page.html',
styleUrls: ['./commerces.page.scss'],
})
export class CommercesPage implements OnInit {
itemListData = [];
commerces = [];
nbCommerce = 10;
constructor(
private httpClient: HttpClient,
private geolocationService: GeolocationService
) {
}
async ngOnInit() {
await this.getAllCommerces(await this.nbPage());
await this.getCommerces(false, "");
}
async getCommerces(isFirstLoad, event) {
var tmp = [];
for (let i = 0; i < 10; i++) {
tmp.push(this.itemListData[i]);
}
this.nbCommerce = + 10
if (isFirstLoad) {
event.target.complete();
}
this.commerces = tmp;
}
doInfinite(event) {
this.getCommerces(true, event);
}
async sort() {
this.itemListData.sort(function (a, b) {
if (a.title.rendered > b.title.rendered)
return 1;
if (a.title.rendered < b.title.rendered)
return -1;
else
return 0;
});
}
onSearchChange(event) {
console.log(event.detail.value);
}
async nbPage() {
const t = this.httpClient
.get('https://example.com/wp-json/wp/v2/listing', { observe: 'response' }).toPromise();
return (await t).headers.get('X-WP-TotalPages');
}
async getAllCommerces(pages) {
for (let j = 1; j <= pages; j++) {
this.httpClient
.get('https://example.com/wp-json/wp/v2/listing?page=' + j, { observe: 'response' })
.subscribe((data: any) => {
for (let i = 0; i < data.body.length; i++) {
data.body[i].location = this.geolocationService.getDistance(data.body[i]._geolocation_lat, data.body[i]._geolocation_long).toFixed(2);;
data.body[i]._gallery = data.body[i]._gallery[Object.keys(data.body[i]._gallery)[0]]
this.itemListData.push(data.body[i]);
}
})
}
await this.sort();
}
}
If you have any suggestions on how to achieve this sequential function execution in Ionic and Angular, please share your thoughts.