top of page

Anguler js - Display data from a JSON file in an Angular CLI project

  1. Create a new Angular CLI project or open an existing one.

  2. Place your JSON file in the src/assets directory of your Angular project. For example, let's say your JSON file is named p4n.json, so the file path would be src/assets/p4n.json.

  3. In your Angular component where you want to display the data, import the HttpClient module and inject it into the constructor. The HttpClient module allows you to make HTTP requests and retrieve data from external files.

  4. In your Angular component where you want to display the data, import the HttpClient module and inject it into the constructor. The HttpClient module allows you to make HTTP requests and retrieve data from external files.

import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) {}

In the ngOnInit() method of your component, use the HttpClient to fetch the JSON data from the file.

ngOnInit() {
  this.http.get('assets/p4n.json').subscribe((p4n) => {
    console.log(p4n); // Verify if the data is fetched correctly
    // Assign the data to a component property
    this.p4n= p4n;
  });
}

In your component's HTML template, you can now use Angular's data binding syntax to display the data.

<ul>
  <li *ngFor="let item of p4n">{{ item.name }}</li>
</ul>
  1. In this example, we assume that the JSON file contains an array of objects with a name property. Adjust the template code to match the structure of your JSON data.

  2. Make sure to import the HttpClientModule in your app module to enable the HttpClient.

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    // ...
    HttpClientModule,
  ],
  // ...
})
export class AppModule {}
  1. Run your Angular CLI project using ng serve and navigate to the component's route to see the data displayed.

This is a basic example of how to display data from a JSON file in Angular CLI. You can customize the code based on your specific JSON structure and component requirements.



Related Posts

See All

Comments


bottom of page