I'd like to create an Angular component containing a dropdown/select where the user can select between several methods from several services, and the selected method will be called on selection change. Those methods are wrappers for different HTTP calls
I want to do it in such a way, that ideally there will be one object (single source of truth) containing all the necessary information like:
export const METHODS = [
{
label: "Get items for overview",
description: "Request retrieving the list of items displayed in the overview"
method: OveriewService.getItems // the getItems method from the Overview Service
}, {
label: "Get detailed overview data",
description: "Request retrieving the detailed data for the overview"
method: OveriewService.getDetailedData // the getDetailedData method from the Overview Service
},{
label: "Get users",
description: "Request retrieving the list of users"
method: UserService.getUsers // the getUsers method from the User Service
}
]
The component
import METHODS from 'path/to/definitions'
@Component({
selector: 'app-data-sandbox',
templateUrl: './data-sandbox.component.html',
styleUrls: ['./data-sandbox.component.scss'],
})
export class DataSandboxComponent implements OnInit {
methods = METHODS;
data = {};
constructor(private overviewService: OveriewService, usersService: UserService) {}
callSelectedMethod(method) {
method({} as HttpParams).subscribe(response => {
this.data = response;
});
}
}
use .bind(service), because you need the clearfy the right instance for "this". You lost your right "this" reference in the Array, but with the .bind() you paste the right "this" context into your service function.
Example:
protected readonly METHODS = [
{
label: 'getOne',
desc: 'one',
method: this.oneService.getOne.bind(this.oneService),
},
{
label: 'getTwo',
desc: 'two',
method: this.oneService.getTwo.bind(this.oneService),
},
{
label: 'getThree',
desc: 'three',
method: this.oneService.getThree.bind(this.oneService),
},
];
change(index: number) {
this.METHODS[index].method().subscribe((data: any) => {});
}