Json 如何修复TypeError:req.url.toLowerCase不是函数

Json 如何修复TypeError:req.url.toLowerCase不是函数,json,angular,angular-services,Json,Angular,Angular Services,我正在设置一个服务,我想首先使用一个带有模拟数据的json文件。然而,我得到一个TypeError:req.url.toLowerCase不是一个函数,当我对模拟数据使用该服务时,如何解决这个错误 服务: import mockCompetitions from '../../mocks/competitions-mock.json'; export class CompetitionsService { constructor(protected http: HttpClient) {

我正在设置一个服务,我想首先使用一个带有模拟数据的json文件。然而,我得到一个TypeError:req.url.toLowerCase不是一个函数,当我对模拟数据使用该服务时,如何解决这个错误

服务:

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模拟网站,如。将JSON文件放在那里,并在
http.get()
中使用站点为您生成的URL。除了代码中的内容,您无需更改任何内容。

要将json文件用作数据提供程序,您可以使用import和require

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

如果要使用httpclient读取本地json文件,请将json文件作为文件名.json放置在assets文件夹中,并使用assets文件夹作为url发出http请求。重要的是要将其放在assets文件夹中,以便Angular可以找到它。因此,您的代码应该如下所示:

export class CompetitionsService {

  constructor(protected http: HttpClient) { }

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

因此无需导入文件。

什么是
mockcompetities
,它不是未定义的吗?至少它是根据您的代码而定的。
mockCompetitions
应该是从中提取数据的json文件吗?如果是,您能否显示
mockCompetitions
@ajt82抱歉,我忘了提到我从项目中的另一个文件夹导入了json文件,因此mockCompetitions包含该文件。您正在使用json文件作为http get的url。@如果是这种情况,请检查该文件是否位于项目中的文件夹中。如果它在您的项目之外,浏览器可能无法拾取文件,因此可能会触发错误这对我不起作用。它根本无法通过require解析.json文件。使用角度8