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

Time:07-15

Trying to update the array value inside the http get method. But, it is not working. Get method also not working to get json data from assets folder.Getting status 200 message. So, How to relsove this issue?

app.component.ts:

ngOnInit(): void { 
    this.httpClient.get<any>('assets/data.json').subscribe((data) => {
      console.log(data);
      this.selectOptions = data;
    });
  }

Demo: https://stackblitz.com/edit/angular-ivy-wwey8k?file=src/app/app.module.ts,src/app/app.component.ts

CodePudding user response:

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.

CodePudding user response:

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