Javascript 为什么显示错误:CastError:Cast to ObjectId值“失败”$本.categoryId“文件;在路径上“;类别“;对于“型号”;产品;?

Javascript 为什么显示错误:CastError:Cast to ObjectId值“失败”$本.categoryId“文件;在路径上“;类别“;对于“型号”;产品;?,javascript,angular,typescript,mongoose,Javascript,Angular,Typescript,Mongoose,我在后端使用nodejs和MongoDB来创建我的应用程序,并将其连接到前端。当我试图从邮递员那里获得特定“类别”下“产品”的价值时,邮递员用成功信息回应并传递价值。但当我试图通过前端查看时,真正的问题出现了 当我尝试获取特定类别内的产品时,它显示以下错误: CastError: Cast to ObjectId failed for value "$this.categoryId" at path "category" for model "P

我在后端使用nodejs和MongoDB来创建我的应用程序,并将其连接到前端。当我试图从邮递员那里获得特定“类别”下“产品”的价值时,邮递员用成功信息回应并传递价值。但当我试图通过前端查看时,真正的问题出现了

当我尝试获取特定类别内的产品时,它显示以下错误:

CastError: Cast to ObjectId failed for value "$this.categoryId" at path "category" for model "Product"
    at model.Query.exec
我已经检查了后端,它运行顺利,没有任何错误。我猜这个错误意味着'categoryId'参数没有得到有效的值,但不能得到,因为我的本地主机被重定向到单个categoryId链接
http://localhost:4200/categories/5f004ae05ca53a0da8d5c043
但它无法在类别内加载产品

下面是我如何在TypeScript
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) {
      
    }
  }

}

如何解决此问题?我希望得到积极的回应。

在代码末尾的
try catch
块中,您似乎错误地将请求URL包装为普通引号
'
,而不是反勾号
`

这就是为什么mongoose显示cast错误,因为它无法解析
$this.categoryId
。请尝试以下方法:

  const data = await this.rest.get(
    `http://localhost:397/api/categories/${this.categoryId}?page=${this.page -1}`
  );

发布服务器端代码,删除角度代码哇,我一直在发送正常引号中的所有链接,但我不知道它们之间的区别。我很感激你,朋友。再次感谢你。