Angular2服务加载JSON,并返回特定的JSON节点/属性

时间:2016-05-24 09:36:39

标签: typescript angular

我目前正在教自己Angular2并且有一些出牙问题(至少可以说)。无论如何,我希望创建一个加载静态JSON文件的服务。目前我正在使用i18n文件,因为他们已经构建了JSON。该服务还将有一个方法,它将接受传递的参数(参数),然后将查找带有传递参数名称的JSON属性。听起来很简单但我有几个问题,首先关闭的是我的服务我想象中称为ContentService,文件是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....
    }
}

在我导入服务的另一个组件中......

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并且在控制台中我正在返回" underfined"。如何让我的方法可以访问我的服务的loadedContent属性?

BTW:这是我的静态JSON文件的内容,它正在服务中加载......

{
  "promotion": {
    "pageTitle": "Oh we have a lovely promotion today..."
  }
}

提前致谢!

1 个答案:

答案 0 :(得分:3)

我会修改你的服务以使其异步:

import {Observable} from 'rxjs/Rx';

@Injectable()
export class ContentService {
  loadedContent: any; // will create a real type later
  obs: Observable<any>;

  constructor(private http: Http) {
    let userLang:string = navigator.language.split('-')[ 0 ];
    userLang = /(en|de)/gi.test(userLang) ? userLang : 'en';

    this.obs = this.http.get('src/i18n/' + userLang + '.json')
      .map((res:Response) => res.json())
      .do(res => this.loadedContent = res);
  }

  getContent(selector) {
    if (this.loadedContent) {
      return Observable.of(this.loadedContent);
    } else {
      return this.obs;
    }
  }
}

并在组件中以这种方式使用它:

@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.contentService.getContent('promotion').subscribe(content => {
      this.content = content;
    });
  }
}

另一个选项也可能是异步引导您的应用程序。有关详细信息,请参阅此问题: