Search code examples
angularrxjsangular-httpclient

Angular HttpClient Object to Array


I have an HttpClient call in Angular 6 that responds with a single object but what I need is an Array. How can I convert the single object returned by the service into an Array that has the single object in it?

I've tried the tap and map operators in Rxjs but think I am missing something simple somewhere. Code is below:

  search(): Observable<TrainInfo[]> {
    return this.http
      .get<TrainInfo[]>(this.SEARCH_URL)
      .pipe(
        // ??? Something here to convert TrainInfo object returned by get into TrainInfo[]
      );
  } 

TLDR: search_url returns one object (TrainInfo), actually need Array (TrainInfo[])


Solution

  • Map is the operator you were looking for. If search_url always returns a single TrainInfo, this should do the trick:

    search(): Observable<TrainInfo[]> {
      return this.http
        .get<TrainInfo>(this.SEARCH_URL)
        .pipe(
          map(value => [ value ]));
    }