Angular - HttpClient: Map Get method object result to array property

后端 未结 5 606
忘了有多久
忘了有多久 2021-02-04 06:19

I am calling an API that returns a JSON Object. I need just the value of the array to map to a Observable . If I call api that just returns the array my service call works.

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 06:28

    You can simply .map() your http call, which is an Observable, to return the data type that you want.

    findAllShows(): Observable {
        return this.http
            .get(`${someURL}/shows`)
            .map(result=>result.shows)
    }
    

    Your httpClient.get() should return an Observable, which you have explicitly stated it thought Observable. You .map() is an operator that transform the observable into a new one.

    More on .map() operator: http://reactivex.io/documentation/operators/map.html

    Update:

    For RXJS version 6 and above, simply use .pipe() to pipe the .map() operator:

    findAllShows(): Observable {
        return this.http
            .get(`${someURL}/shows`)
            .pipe(map(result=>result.shows))
    }
    

提交回复
热议问题