My application is built using nodejs with MongoDB in the backend and Angular in the front-end. When attempting to retrieve values for 'products' within a specific 'category' using Postman, it successfully delivers the values. However, an issue arises when trying to display this data on the front-end.
Upon trying to access the products within the specific category, I encounter the following error:
CastError: Cast to ObjectId failed for value "$this.categoryId" at path "category" for model "Product"
at model.Query.exec
I have verified that the backend is functioning correctly without any errors. It seems like the error may be related to the 'categoryId' parameter not receiving a valid value, even though my localhost redirects to the individual categoryId link
http://localhost:4200/categories/5f004ae05ca53a0da8d5c043
. However, the products inside the category are not loading.
Below is the TypeScript code from my category.component.ts
:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router' ;
import { RestApiService } from '../rest-api.service' ;
import { DataService } from '../data.service';
@Component({
selector: 'app-category',
templateUrl: './category.component.html',
styleUrls: ['./category.component.scss']
})
export class CategoryComponent implements OnInit {
categoryId: any;
category: any;
page = 1;
constructor(
private data: DataService,
private activatedRoute: ActivatedRoute,
private rest: RestApiService
) { }
ngOnInit() {
this.activatedRoute.params.subscribe(res => {
this.categoryId = res['_id'];
this.getProducts();
});
}
get lower() {
return 10 * (this.page - 1) + 1;
}
get upper() {
return Math.min(10 * this.page, this.category.totalProducts);
}
async getProducts(event ?: any) {
if (event) {
this.category = null;
}
try {
const data = await this.rest.get(
'http://localhost:397/api/categories/$this.categoryId?page=${this.page -1}'
);
data['success']
? (this.category = data)
:this.data.error(data['message']);
}catch (error) {
}
}
}
Any suggestions on how to resolve this issue? I look forward to hearing positive responses.