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';

  providedIn: 'root'
export class DataService {
  data = Data;

  getItems() {

  constructor() {}

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';

    private dataService: DataService
  ) { }

  ngOnInit(): void {



3. Summary

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


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

Leave a Reply

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