Global JSON data service in Angular

A simple method for loading and sharing JSON data across an Angular app using a shared service.

1. Create the service

Create a the service file in the src/shared folder:

// FILE: ./shared/data.service.ts

import { Injectable } from '@angular/core';
import * as Data from 'path/to/data.json';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  data = Data;

  getItems() {
    return this.data;
  }

  constructor() {}
}Code language: JavaScript (javascript)

2 Use the service

To use the service you need to import it:

// FILE: "some.component.ts"

import { DataService } from './shared/data.service';

...

export class SomeComponent implements OnInit {
  title = 'Some Title';

  constructor(
    private dataService: DataService
  ) { }

  ngOnInit(): void {
    console.log(this.dataService.getItems());
  }

}

...Code language: JavaScript (javascript)

3. Summary

You have created a shared service for loading JSON data, which can be imported across an app as desired.


Troubleshooting:

Error: “Cannot find module ‘./path/to/data.json’. Consider using ‘–resolveJsonModule’ to import module with ‘.json’ extension”. If you come across this error, take a look at step 1 in this article.

Related links

https://angular.io/start/start-data

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.