Reputation: 309
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
Upvotes: 0
Views: 899
Reputation: 23664
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
})
});
}
Upvotes: 1