I'm currently teaching myself Angular2 and having a few teething problems (to say the least). Anyway, I wish to create a service that loads a static JSON file. For the time being I am using i18n files as they have structured JSON. The service will also have a method that will take a passed parameter (an argument) and will then look for the JSON property with the name of the passed parameter. Sounds pretty simple but I have a few questions, first off all here is my service I imaginally called ContentService, the file is content.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http'
@Injectable()
export class ContentService {
loadedContent: any; // will create a real type later
constructor(private http: Http) {
// 1. Determine the language
let userLang:string = navigator.language.split('-')[ 0 ];
userLang = /(en|de)/gi.test(userLang) ? userLang : 'en';
// 2. Load the file... I should really use interpolation for the file path
this.http.get('src/i18n/' + userLang + '.json').map((res:Response) => res.json()).subscribe(res => this.loadedContent = res);
}
getContent(selector) {
// in here we need to pass the selector and fetch the content from the loaded JSON, however for now I will just return the passed selector and see if I have access to the loadedConent
console.log(selector, this.loadedContent); // this.loadedContent is undefined!
// we need a catch for we the selector is not found....
}
}
in another component I import the service...
import { ContentService } from '../content/content.service';
@Component({
selector: 'angular2-test',
providers: [ ContentService ],
templateUrl: 'src/home/home.template.html'
})
export class TestComponent {
content: any; // real type to come later
constructor(private contentService: ContentService) {
this.content = this.contentService.getContent('promotion')
}
}
Now obviously I have a bit of an error as in my getContent method I have no access to this.loadedContent and in the console I am returning "underfined
". How can I get my method to have access to the loadedContent
property of my service?
BTW: this is the content of my static JSON file and it is loading in the service...
{
"promotion": {
"pageTitle": "Oh we have a lovely promotion today..."
}
}
Thanks in advance!