One of the services in my application utilizes a dictionary to store HTTP responses, mapping an ID to a specific URL.
import { HttpClient} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class urlService {
private map: Map<string, string>;
constructor(private http: HttpClient) {
this.map = new Map<string, string>();
}
public getUrl(id: string): Observable<string> {
if (this.map.has(id)) {
return of(this.map.get(id));
}
this.http.get<any>(`...sampleURL...`)
.subscribe((result) => {
this.map.set(id, result.url);
return of(this.map.get(id));
});
}
}
However, despite my efforts, when I attempt to retrieve this URL
from my app component, the result is consistently undefined
.
this.urlService.getUrl(this.id).subscribe(
url => console.log(url)
);
It seems that the problem lies in the subscription returning an Observable
within urlService.getUrl()
. Can anyone provide some guidance on how to address this issue?
I did attempt to use switchMap
as a solution, but unfortunately, it did not resolve the problem.
this.http.get<any>(`...sampleUrl...`).pipe(
switchMap(result => {
this.map.set(id, result.url);
return of(this.map.get(id));
}))
.subscribe();