1

Maybe a easy question, but I couldn't find a example for this.

This is my HttpClient call

getItems(dataSourceUrl: string, bindKey: string, bindValue: string): Observable<SelectItem[]> {
    return this.httpClient.get<Array<any>>(dataSourceUrl);
}

I want to map the list result to SelectItem[] based on bindKey and bindValue. How do I do that?

I tried something like this

return this.httpClient.get<Array<any>>(dataSourceUrl).pipe(map(x=> { return { label: data.bindKey, value: data.bindValue } }));

Interface

export interface SelectItem {
    label: string;
    value: any;
}

Example of two different api responses

1.

{key:'Istanbul', value: 'Test' }
{key:'London', value: 'Test' }

bindKey will be key bindValue will be value

2.

{name:'Istanbul', id: 'Test' }
{name:'Istanbul', id: 'Test' }

bindKey will be id bindValue will be name

3
  • I use typestack/class-transformer decorators to convert plain objects to class instances and vice versa. I recommend you to have a look at Commented Apr 9, 2019 at 11:00
  • Can u show us what is interface of SelectItem and what is the API response. In the code shared, Also, I cant see data object which you are using as data.bindKey . Am i missing something ? Best thing would be to share API response and expected response after applying map Commented Apr 9, 2019 at 11:07
  • @ShashankVivek the api response can be a list of any type. That's why I want to map it dinamicaly, based on bindKey , bindValue - both of them properties of the items from the list api response Example of two api responses {key:'Istanbul', value: 'Test' } {name:'Istanbul', id: 'Test' } bindKey will be: key, id. bindValue will be name, value. Commented Apr 9, 2019 at 11:13

1 Answer 1

1

Try

getItems(dataSourceUrl: string, bindKey: string, bindValue: string): Observable<SelectItem[]> {
     return this.httpClient.get<SelectItem[]>(dataSourceUrl)
           .pipe(map(x=> this.transformValue(bindKey,bindValue,x)));
}

transformValue(bindKey,bindValue,response):SelectItem[]{
    const newResponse = [];
    response.forEach(data => {
        newResponse.push({
            label: data[bindKey],
            value: data[bindValue]
        })
    })
    return newResponse;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Somehow I thought, that .map can do this automagically without a forEach

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.