TheAnonymousModeIT
TheAnonymousModeIT

Reputation: 913

Convert Angular HttpClient result

I have the following code:

getData(config: IConfig): Observable<IDataItem> {
    return this.http
        .get<IDataItem>(url);
}

That works fine. But I need to return a data structure like this:

result = {
 id: config.id,
 payload: httpCallPayload
}

How can I do this?

Upvotes: 0

Views: 27

Answers (1)

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

You can use map pipeable operator of RxJs like following:

getData(config: IConfig) {
    return this.http.get<IDataItem>(url).pipe(
        map((httpResult) => {
            return {
               id: config.id,
               payload: httpResult
            }
        })
    );
}

Note that the return type Observable<IDataItem> is removed because it will throw an error. You can create an interface for the return type like {id: string|number, payload: IDataItem} to define the return type of getData() method.

For further reading: https://www.learnrxjs.io/operators/transformation/map.html

Upvotes: 1

Related Questions