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.