Search code examples
jsonangularangular-services

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


I'm setting up a service and i want to use a json file with mock data to start with. However i get a TypeError: req.url.toLowerCase is not a function when i use that service with the mock data, how can i resolve this error?

Service:

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

export class CompetitionsService {

  constructor(protected http: HttpClient) { }

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

Component:

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...'));
  }

I expect a list of names to be printed out on the page from the json file.


Solution

  • If you want to use httpclient to read local json file, put the json file in assets folder as name-of-the-file.json and make the http request by using assets folder as url. It is important that you put it in the assets folder, so that Angular can find it. So your code should look something like this:

    export class CompetitionsService {
    
      constructor(protected http: HttpClient) { }
    
      getCompetitions() {
         return this.http.get('./assets/name-of-the-file.json');
      }
    }
    

    So no need to import the file.