So I have a service that uses a dictionary to store HTTP responses (maps 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, when I try to get this url
from my app component, the logged value is undefined
.
this.urlService.getUrl(this.id).subscribe(
url => console.log(url)
);
I suppose this is because in urlService.getUrl()
I have a subscription returning an Observable
. Can anyone point me in the right direction to solve this issue?
I tried using switchMap
, but that didn't seem to help.
this.http.get<any>(`...sampleUrl...}`).pipe(
switchMap(result => {
this.map.set(id, result.url);
return of(this.map.get(id));
}))
.subscribe();