Hey I'm trying to implement a bootstrap5 dropdown following this example: Creating Multi-Select Dropdown with Angular and Bootstrap 5 In that example, to get the data, he uses an app.service and just returns an array of objects:
getFoods(): Food[] {
return [
{
id: 1,
name: 'Grapes'
},
{
id: 2,
name: 'Melon'
},
...
And then in his ngOnInit() calls the getFoods() method and also uses .map() operator because he has to assign to values because the item model has two values:
ngOnInit(): void {
this.items = this.appService.getFoods().map(fruit => ({
id: fruit.id,
name: fruit.name
} as Item));
}
So I'm trying to do hat but with data being fetched from an API endpoint using HTTP GET request. But I don't know how to use the .map() operator for the http get request:
this.subscription = this.contactSearchService.currentCodes.pipe(
map(
code => (
{
id: code.code,
name: code.code
}
)
)).subscribe(Response => {
this.items = Response
})
It's giving me these errors:
Property 'code' does not exist on type 'ResponsibilityCode[]'.
Type '{ id: any; name: any; }' is missing the following properties from type 'Item[]': length, pop, push, concat, and 26 more.
My http get request function:
private _reponsibilityCodeSource = new BehaviorSubject<ResponsibilityCode[]>([]);
currentCodes = this._reponsibilityCodeSource.asObservable();
getCodes(): void {
this.http.get<ResponsibilityCode[]>('https://localhost:44316/api/SITEContacts/ResponsibilityCode').subscribe(Response => {
this._reponsibilityCodeSource.next(Response);
});
}
I get the data as `JSON` btw.
The rxjs pipe(map(.... code...)) is different than array.map -
pipe(map()) does not operate on each item of an array
So the errors you are getting is because you're swapping out the array of ResponsibilityCode for a single item (code in your code is all the responsibility codes)
Try
this.subscription = this.contactSearchService.currentCodes.subscribe(Response => {
this.items = Response.map(
code => (
{
id: code.code,
name: code.code
}
)
)
})
Your HTTP get returns an Observable of ResponsibilityCode array, so to achieve that you have to map (Array.prototype.map) the items of the array within the RxJS's map operator, like the following:
this.subscription = this.contactSearchService.currentCodes
.pipe(
map((res: ResponsibilityCode[]) =>
res.map((item) => ({
id: item.id,
name: item.name,
}))
)
)
.subscribe((res) => {
this.items = res;
});