現在、私はAngular2を教えていますが、いくつかの問題を抱えています。とにかく、静的なJSONファイルをロードするサービスを作成したいと考えています。 JSONを構造化しているので、当面はi18nファイルを使用しています。また、渡されたパラメータ(引数)を受け取り、渡されたパラメータの名前を持つJSONプロパティを検索するメソッドもあります。かなり簡単に聞こえるが、私はいくつかの質問を持って、最初のオフすべてここJSONをロードし、特定のJSONノード/プロパティを返すAngular2サービス
...ファイルが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....
}
}
で、私はimaginally ContentServiceと呼ばれる私のサービスであり、
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')
}
}
明らかに、私はgetContentメソッドのように私はthis.loadedContentへのアクセス権がなく、コンソールで私は ""を返しています。私の方法で私のサービスのloadedContent
プロパティにアクセスするにはどうしたらいいですか?
ところで:これは私の静的なJSONファイルの内容であり、それはサービスにロードされています...事前に
{
"promotion": {
"pageTitle": "Oh we have a lovely promotion today..."
}
}
ありがとう!
おかげで、しかし、私はあまりにも/タイプをthis.obs与える私のサービスのトップでそれを宣言する必要があると仮定しますか?また、RxJSからObservableをインポートする必要があります –
大歓迎です!はい、それは 'Observableである可能性があります' ... –
あまりにもリンクのためにありがとう!私は '解決されていないメソッドや関数についての警告を受け取りますが、私はそれを使って暮らすことができます。実際のJSONをもっと大きくするためにコードを書くことができます。どうもありがとう! –