Tony Scialo
Tony Scialo

Reputation: 5957

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[])

Upvotes: 1

Views: 993

Answers (1)

Dean
Dean

Reputation: 2273

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 ]));
}

Upvotes: 1

Related Questions