After spending an entire day trying to come up with a solution, I've hit a roadblock and now I'm seeking some help.
WHAT I REQUIRE
I need to create a service that returns an array of objects. Initially, these objects are fetched from a web service using HttpClient, but I want to store them in a local variable to avoid unnecessary time and bandwidth consumption every time the service is called. Finally, I need to display these objects in a <select *ngFor
tag and set a default value once the values are loaded.
INITIAL APPROACH
service.ts
stati = null;
getStati() {
if (this.stati) return this.stati;
return this.http.get<ApiResponse>(this.apiUrl + 'lists/stati')
.pipe(
retry(3),
map(data => {
if (data.status === 0)
this.stati = data.response; // <-- this is an array
return this.stati;
}
));
}
request.component.ts
this.svcApi.getStati()
.subscribe((stati) => {
this.stati = stati;
this.request.nascita.stato = 'IT';
this.request.residenza.stato = 'IT';
});
request.component.html
<select class="form-control"
[(ngModel)]="request.nascita.stato" name="stato">
<option *ngFor="let stato of stati"
[value]="stato.codice">{{stato.nome | uppercase}}</option>
</select>
This approach works fine only the first time. However, when my router (re)activates the route, I encounter an error in the component stating that svcApi.getStati().subscribe
is not a function; understandably so, as this time it doesn't return an Observable but an array instead!
SECOND ATTEMPT
I attempted to modify the service function like this:
if (this.stati) return Observable.from(this.stati);
But upon returning to the route, I encounter this console error:
ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
THIRD ATTEMPT
For my final attempt, I also tried to change
<option *ngFor="let stato of stati | async"
However, this resulted in another error:
ERROR TypeError: Cannot read property 'dispose' of null at AsyncPipe.push
I am confident that there must be a simple solution to this issue, but being new to this, I'm struggling to find it.