I am relatively new to Angular/Typescript and facing a challenge. In my ngOnInit()
, I am trying to fetch settings from my backend using a GET request. After that, I need to subscribe to an observable. The observable updates the widgets' content over time while the settings determine the number and type of widgets to display.
Essentially, I want the ngOnInit()
to wait for the response from getGeneralSettingsOnce
before starting other subscriptions.
This is my request function:
getGeneralSettingsOnce(): Promise<any> {
return this.http.get(`${environment.API_URL}/get_general_settings`).toPromise()
.then(response => {
return response
})
}
Initially, I tried making the ngOnInit
of my main page an async function and awaiting the promise. However, this resulted in the error
Cannot read properties of undefined (reading '-1')
for some static widgets on my main page. As per an article I read, this might be because the main page is not fully loaded when the browser tries to render it. Source: article
Segments of the ngOnInit of my main page
async ngOnInit() {
let generalSettings = await this.localService.getGeneralSettingsOnce(); //calling the promise
this.widgetCount = generalSettings.widget_count
// other subscriptions
this.localService.getWidgetContent().subscribe(
data => { this.loadWidgetContent(data)
}
}
}
My question is how can I achieve my goal of initializing the settings first and then subscribing to other request functions as if it were synchronous, preferably without errors.