I use ASP.NET Core 5 technology for backend and Angular 15.0 for my frontend.
The action of controller in backend to get some filtered items is written as below:
[HttpGet("getAllCustomerPaymentsByDateRange")]
public async Task<IActionResult> GetAllCustomerPaymentsByDateRange([FromQuery] DateTime firstDate,[FromQuery] DateTime endDate,[FromQuery] long customerId )
{
// ... rest of code
}
I want to pass these parameters from a method in an Angular service to the action:
getAllCustomersByDateRange(???): Observable<PaymentForList[]> {
return this.http.get<PaymentForList[]>(this.baseUrl '/getAllCustomerPaymentsByDateRange/', ???);
}
How can I pass parameters to Angular method that are received by the ASP.NET Core controller action correctly? I tried to pass parameters as a model and other side receives it as ([FromBody] ModelParams params)
, but I got error on the Angular side that:
can not assign PaymentForList[] | ArrayBuffer to PaymentForList[]....
Is there another way to do this?
CodePudding user response:
Not recommend sending a request with the body to a GET
API as discussed in HTTP GET with request body.
To pass query parameters, you should use HttpParams.
getAllCustomersByDateRange(firstDate: Date, endDate: Date, customerId: number): Observable<PaymentForList[]> {
let params: HttpParams = new HttpParams();
params = params.append('firstDate', firstDate.toISOString());
params = params.append('endDate', endDate.toISOString());
params = params.append('customerId', customerId);
let httpOptions = {
params: params
};
return this.http.get<PaymentForList[]>(this.baseUrl '/getAllCustomerPaymentsByDateRange/', httpOptions);
}
Refer to HttpClient.get() Overload #15.