1

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();

1 Answers1

2

You are not correctly returning the Observable in the current getUrl method. It doesn't have any return value thus return undefined.

Instead, you should return Observable with the map rxjs operator.

import { map } from 'rxjs';

public getUrl(id: string): Observable<string> {
  if (this.map.has(id)) {
    return of(this.map.get(id));
  }

  return this.http.get<any>(`...sampleURL...`)
      .pipe(
        map((result) => {
          this.map.set(id, result.url);

          return this.map.get(id); 
          // Or 
          // return result.url; 
        })
      );
}

Demo @ StackBlitz

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • 1
    Oh I see, I was subscribing to the HTTP request and 'returning' something there, but that actually doesn't return anything from the `getUrl` method. Thank you! – inquisitivemongoose Apr 08 '23 at 02:40