1

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

3
  • Does search_url ALWAYS return one TrainInfo or can it return one or multiple? Commented Jan 14, 2019 at 23:49
  • 1
    Did you try pipe(map(trainInfo => [trainInfo]))? Commented Jan 14, 2019 at 23:51
  • @ConnorsFan that worked, thanks Commented Jan 15, 2019 at 1:47

1 Answer 1

1

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 ]));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.