Background
In an Angular component, I need to load some settings before to load the data, so I have the following code:
constructor(
private dataService: DataService,
settingsService: SettingsService
) {
settingsService.get().subscribe({
next: (settings) => this.settings = settings
});
}
onInit() {
this.loadData();
}
loadData() {
this.dataService.get(this.settings).subscribe({
next: (data) => this.data = data
});
}
As you can see, this.settings
has to be loaded before to call loadData()
, which is called in the initialization and subsequently when the user press a button. While settingsService.get()
is called just once in the beginning, this.dataService.get()
can be called many times.
Problem
The first loadData()
calling from onInit()
has been called before settingsService.get()
finishes, so the parameter is undefined and I get an error.
Question
How do I synchronize them for this particular situation?
NOTE
There is a similar question at Angular - Make multiple HTTP calls sequentially, but I believe it is a different scenario, because in that case both observers are called every time together, sequentially. In this particular case, I need to synchronize them only on the first time, so I cannot see how switchMap
can be used here. I am not a RXJS expert, so if I'm not right, some tip will be welcome. Thanks.