Reputation: 27
I'm trying to send get request from angular to rest api by using id as a query string route parameter.In controller class i have a action method where i want to receive id as a query string route parameter but i don't know how i have to send request from angular to rest api.
Angular service class get method
getAdvertisement(id: number): Observable<Advertisement> {
return this.http.get<Advertisement>(`${this.baseApiUrl}/api/advertisements?id=${id}`);
}
Component class
**here in this line "this.advertisementService.getAdvertisement(id)" i'm receiving that error "Argument of type 'string | null' is not assignable to parameter of type 'number'." **
export class DetailsComponent implements OnInit {
advDetails: Advertisement={
id: 0,
name: '',
price: '',
description: ''
};
constructor(private route: ActivatedRoute, private advertisementService: AdvertisementsService) { }
ngOnInit(): void {
this.route.paramMap.subscribe(params => {
const id = params.get('id');
this.advertisementService.getAdvertisement(id).subscribe(response =>{
// here in id i'm receiving that error
this.advDetails = response;
});
// if(id != null){
// }
});
}
}
Controller class action method
[HttpGet]
public IActionResult GetAdvertisements()
{
try
{
string temp = Request.Query["id"];
if (!string.IsNullOrWhiteSpace(temp))
{
int id = Convert.ToInt32(temp);
if (id > 0)
{
AdvertisementModel adv = new AdvertisementsHandler().GetAdv(id).ToModel();
return Ok(adv);
}
}
}
catch (Exception ex)
{
return StatusCode(500, ex); //Internal server error;
}
}
Upvotes: 0
Views: 850
Reputation: 629
Your error "Argument of type 'string | null' is not assignable to parameter of type 'number'." **
is caused by passing string to method that requires number.
you can fix it very easily by modifying this method to accept string instead of number
getAdvertisement(id: string): Observable<Advertisement> {
return this.http.get<Advertisement>(`${this.baseApiUrl}/api/advertisements?id=${id}`);
}
The problem is that if for some reason this string will not be a number you will get exception from backend.
Other thing that you can do is to cast it to number in angular:
ngOnInit(): void {
this.route.paramMap.subscribe(params => {
const id = parseInt(params.get('id'));
if (!id) {
//handle case when id is not an integer number
return;
}
this.advertisementService.getAdvertisement(id).subscribe(response =>{
// here in id i'm receiving that error
this.advDetails = response;
});
// if(id != null){
// }
});
}
Upvotes: 0