Currently, I am trying to teach myself Angular2 and facing some difficulties along the way. I am working on creating a service that loads a static JSON file. Right now, I am using i18n files as they are structured in JSON format. The service will include a method that takes a parameter and searches for the corresponding JSON property. It may sound straightforward, but I have a few questions. Here is the service I created called ContentService, which is saved in the file content.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http'
@Injectable()
export class ContentService {
loadedContent: any; // will assign a proper 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... should consider using interpolation for the file path
this.http.get('src/i18n/' + userLang + '.json').map((res:Response) => res.json()).subscribe(res => this.loadedContent = res);
}
getContent(selector) {
// need to fetch content from the loaded JSON based on the selector passed, for now just returning the passed selector
console.log(selector, this.loadedContent); // this.loadedContent is undefined!
// need to handle case when 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 will be added later
constructor(private contentService: ContentService) {
this.content = this.contentService.getContent('promotion')
}
}
I am encountering an error where my getContent method does not have access to this.loadedContent and returns "undefined
" in the console. How can I ensure that my method can access the loadedContent
property of the service?
By the way, here is the content of my static JSON file that successfully loads in the service...
{
"promotion": {
"pageTitle": "Oh we have a lovely promotion today..."
}
}
Thank you in advance!