1

I need to create global dictionary with translations in Angular and I want to use this dictionary in each component. I have created a custom service:

import { Injectable } from "@angular/core";
import _dictionary from "../assets/js/dictionary.json";

interface IWords {
  [key: string]: string;
}

@Injectable({
  providedIn: "root"
})
export class DictionaryService {
  private dictionary = new Map<string, IWords>();

  constructor() {
    console.log(_dictionary);
  }
}

Then I have added this to providers: @NgModule({ providers: [ DictionaryService ]});

As you can see, service uses json file with translations.

Problem is that constructor of service does not work, so I can not see message:

console.log(_dictionary);
3
  • It should not be necessary to add the DictionaryService in the providers array of @NgModule as you have 'providedIn: "root" ' in the service, it does the same thing. Not sure why you can not see your console.log though. Commented Oct 3, 2019 at 19:52
  • Anyway, constructor does not work, I have removed: @Injectable({ providedIn: "root" }) Commented Oct 3, 2019 at 19:59
  • I have figured out, it works only when I use as dependency in component Commented Oct 3, 2019 at 20:05

2 Answers 2

2

You can import json data like this:

import * as _dictionary from "../assets/js/dictionary.json";

However you can't inject it in your constructor. You could include it your service like this:

export class DictionaryService {
  private dictionary = _dictionary;

  constructor() {}
}

Side note, for translations there are great tools out there like ngx-translate and transloco that load json files behind the scenes, and do it really well. I wrote an article explaining how to use them here.

You might need to add "resolveJsonModule": true to your compiler options in your tsconfig.json file.

Sign up to request clarification or add additional context in comments.

Comments

2

To read a JSON file you should use http get and subscribe to it

import { HttpClient } from '@angular/common/http'; 
...
this.http.get("../assets/js/dictionary.json").subscribe(data => {
   console.log(data);
});

Regards

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.