0

For example, I have a json file, "users.json" in below format:

{
  "Users": [
    {
      "name": "Tom"
    },
    {
      "name": "Jim"
    },
    {
      "name": "Julie"
    }
  ]
}

So far, I am able to import UserList from 'users.json' by following this step

I am learning Angular and had no experience in js before. I am stuck how to write the js/ts in angular to declare objects and loop through it in a component. Eventually, I would add these users info to API.

export class addUser OnInit {
  
  # declare user, I am not sure I did right
  users: {name:string} = UserList;

  constructor(
    private APIservice: someAPIservice
  ) {}

  ngOnInit(): void {
    
    ### loop each user, I have no idea now, but give an example
    for (let name in this.users) {
      console.log(users[name])
      ## eventually, I will change code to add each name to APIservice
      ## But I would like to know how to read each name first
    }

What is the best way to read the json file and loop each name in Angular?

Thank you

1 Answer 1

1

You'll want to use the import command for typescript files, not for data. For data, use HttpClient

import { HttpClient, HttpParams } from '@angular/common/http';
constructor(
        private http: HttpClient
);
ngOnInit(): void {

   this.http.get('../data/users.json').subscribe((users: []) => {
      users.forEach((user: any) => {
        // user.name
      })
   });

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

3 Comments

Hi John, Thank you for your answers. However, I got this error GET http://localhost:4200/users.json 404 (Not Found) and I am pretty sure I give right location of json file.
if you're getting a 404 that means you don't have the right location of the json file. Starting the the src directory, where is the data file?
Also I mod'd my answer - Im pretty sure users.json will import as a ready to go json format, so I removed the JSON.parse() line.

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.