0

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%2Fapp%2Fapp.module.ts,src%2Fapp%2Fapp.component.ts

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

5 Comments

your stackblitz not opening properly
I want use inside get method
@EMahanK You will still get errors if you try calling a get request on your json file on stackblitz. stackblitz.com/edit/… But points 1 and 3 still stand on my answer. You should provide a reason as to why you want to call a get request on a file in your assets folder.
The problem is not the get method. ngOninit is calling after loading the <app-mauto></app-mauto> component. So this.rowData is empty from the mauto.component.ts. How to resolve this issue?
@EMahanK Setting up an observable would work then. I'm not sure if you are trying to resolve an issue in your codebase or the stackblitz. But going by your original question the problem lies within both.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.