How to set a array values inside http get method in angular 14

Viewed 192
2 Answers

The problem on stackblitz is, that you are refering to the assets directory, which is actually not public. So your request is correct, because it gets response (code 200), but it's not a valid json, it's the static html file - you can see that in your error log response. If you take the data from the assets folder, it needs to be publicly available while you're making the request.

You have a few problems with your code.

  1. Your data.json file is not in the proper format, it's just an array.

  2. There is no reason to call a get request. JSON files can be imported by adding a setting the resolveJsonModule to true in your .tsconfig so you can import it:

    import testdata from './assets/data.json';

  3. Your assets folder is not named assets in the stackblitz but ässets

Change your json data to this:

{"data": ["Car", "Bus", "Fuel", "Motor"]}

And in your ngOnInit to this:

  ngOnInit(): void {
   //this.selectOptions = ['Bus', 'Car', 'Motor', 'Wheel'];
   this.selectOptions = testdata.data;
  }

Stackblitz: https://stackblitz.com/edit/angular-ivy-h9fezk

Related