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.
Your data.json file is not in the proper format, it's just an array.
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';
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