Salman Kazmi
Salman Kazmi

Reputation: 3248

Getting JSON values/properties from a file in a component in angular 4

There is a set of components in my Angular 4 app in which each component requires a certain set of properties from a different JSON file which it shows on its template. I have created a common JSON file containing all the properties and I load it when the app-component is called using a service that holds those properties array.

I then inject that same service into different components and fetch the populated array. The values show in the HTML all fine.

However, this approach seems to be a bit time consuming especially when the constants grow in size. Loading thousands of constants all at once and injecting them into different components where few of them are required is not a good approach.

I was willing to work on an approach where I create specific contansts JSON file for each component and somehow load it when the component is actually initialized. This way I can save the burden of a heavy JSON object and only those properties would be loaded that are required by that component.

The load() method in my constants service looks something like this:

@Injectable()
export class ConstantsService {
constructor(private http: HttpClient) {
    console.log('ConstantsService created');
}
    constants = {};
    load() {
        var constants = {};
        var cons = 'constants';

        var constantsResourceUrl =
            'path' + cons + '.json';

        this.http.get(constantsResourceUrl)
            .subscribe(result => {
                this.constants = result;
            },
            error => this.log.error(constantsResource + ' could not be loaded')
            );
    }
}

And my Components look like this to get the value of the constants:

@Component({
  selector: 'xyz',
  templateUrl: './xyz.html',
  styleUrl: './xyz.css'
})
export class MyComponent {
  consts = {};

  constructor(private constantsService: ConstantsService) {

    consts = this.constantsService.constants;
  }
}

Any help would be appreciated.

Upvotes: 0

Views: 493

Answers (1)

MRsa
MRsa

Reputation: 684

If did have similar dilema. To use db or json files for settings/parametars behavior. Dynamic content end up in db, and at the end I found that is little stupid to fetch and use http request to get static json content since that could be bundled in source. I did split it and use in multiple exported constant in ts. file like:

export const dummyLookupConst = `{ "queryNo": 0, "id": 250, ...}

and then import it into components by need.

Upvotes: 1

Related Questions