Categories
Angular Answers

How to load JSON from local file with http.get() in Angular and TypeScript?

Spread the love

Sometimes, we want to load JSON from local file with http.get() in Angular and TypeScript.

In this article, we’ll look at how to load JSON from local file with http.get() in Angular and TypeScript.

How to load JSON from local file with http.get() in Angular and TypeScript?

To load JSON from local file with http.get() in Angular and TypeScript, we call get with the relative path to the JSON.

For instance, we write

//...
export class AppComponent {
  private URL = "./assets/navItems.json";
  //...

  constructor(private httpClient: HttpClient) {}

  ngOnInit(): void {
    this.httpClient
      .get(this.URL)
      .subscribe((navItems) => (this.navItems = navItems));
  }
}

to call httpClient.get with the URL to the JSON.

Then we call subscribe with a callback to get the navItems response and set it as the value of this.navItems.

Conclusion

To load JSON from local file with http.get() in Angular and TypeScript, we call get with the relative path to the JSON.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *