How to fix TypeError: req.url.toLowerCase is not a function

How to fix TypeError: req.url.toLowerCase is not a function

我正在设置一项服务,我想使用包含模拟数据的 json 文件作为开始。但是我得到一个 TypeError: req.url.toLowerCase is not a function 当我将该服务与模拟数据一起使用时,我该如何解决这个错误?

服务:

import mockCompetitions from '../../mocks/competitions-mock.json';

export class CompetitionsService {

  constructor(protected http: HttpClient) { }

  getCompetitions() {
     console.log(mockCompetitions);
     return this.http.get(mockCompetitions);
  }
}

组件:

competitions: any = [];

  constructor(private competitionsService: CompetitionsService) {}

  ngOnInit(){
    this.getCompetitions();
  }

  getCompetitions(){
    this.competitionsService.getCompetitions().subscribe(data => {
      this.competitions = data;
      console.log(this.competitions);
    }, err => console.error(err), () => console.log('Finished Loading...'));
  }

我希望从 json 文件的页面上打印出一份姓名列表。

您正在使用 JSON 文件作为您 http.get() 的 url。 如果您想使用模拟数据测试您的服务,我会推荐一些 HTTP 模拟网站,例如 mocky。将您的 JSON 文件放在那里,并在您的 http.get() 中使用网站为您生成的 URL。除了代码中的内容外,您无需更改任何内容。

要使用 json 文件作为数据提供者,您可以使用 import 和 require。

import data = require('your_file.json')
console.log("data : ", JSON.stringify(data));

如果要使用httpclient 读取本地json 文件,将json 文件放在assets 文件夹中作为name-of-the-file.json 并使用assets 文件夹作为[=] 发出http 请求19=]。将它放在资产文件夹中很重要,这样 Angular 才能找到它。所以你的代码应该是这样的:

export class CompetitionsService {

  constructor(protected http: HttpClient) { }

  getCompetitions() {
     return this.http.get('./assets/name-of-the-file.json');
  }
}

所以不需要导入文件。