javascript – Angular2等到加载JSON文件

目前我正在加载一个
JSON文件,如下所示:

translation.service.ts

@Injectable()
export class TranslationService {

    private _messages = [];

    constructor(private _http: Http) {
        var observable = this._http.get("/app/i18n/localizable.it.strings").map((res: Response) => res.json());
        observable.subscribe(res => {
            this._messages = res;
        });
    }

    getTranslationByKey(key: string, args?: any[]) {
        return this._messages[key];
    }
}

localizable.it.strings

{
    "home.nav.calendar": "Calendar",
    ...
}

我的TranslationService被注入到我的HomeComponent中,但问题是当我尝试通过管道读取这些值时,它们仍然需要在呈现页面时加载.

translate.pipe.ts

@Pipe({name: 'translate'})
export class TranslatePipe implements PipeTransform {

    constructor(private _translation: TranslationService) {}

    transform(value: string, args: string[]) : any {
        return this._translation.getTranslationByKey(value);
    }
}

知道如何在加载任何页面之前从JSON文件加载所有值吗?

最佳答案 我认为您可以调整一下您的服务和管道,以便在数据准备/加载时进行处理.

首先添加一个observable,以便在服务中加载数据时通知:

@Injectable()
export class TranslationService {

  private _messages = {};

  private translationLoaded : Observable<boolean>;
  private translationLoadedObserver : Observer<boolean>;

  constructor(private _http: Http) {
    this.translationLoaded = Observable.create((observer) => {
      this.translationLoadedObserver = observer;
    });

    var observable = this._http.get("app/i18n/localizable.it.strings").map((res: Response) => res.json());
    observable.subscribe(res => {
      this._messages = res;
      this.translationLoadedObserver.next(true);
    });
  }

  getTranslationByKey(key: string, args?: any[]) {
    return this._messages[key];
  }
}

管道可以在此observable上订阅,以与async相同的方式透明地更新消息的值:

@Pipe({
  name: 'translate',
  pure: false  // required to update the value when data are loaded
})
export class TranslatePipe implements PipeTransform {
  constructor(private _ref :ChangeDetectorRef, private _translation: TranslationService) {
    this.loaded = false;
  }

  transform(value: string, args: string[]) : any {
    this.translationLoadedSub = this._translation.translationLoaded.subscribe((data) => {
      this.value = this._translation.getTranslationByKey(value);
      this._ref.markForCheck();
      this.loaded = true;
    });

    if (this.value == null && this.loaded) {
      this.value = this._translation.getTranslationByKey(value);
    }
    return this.value;
  }

  _dispose(): void {
    if(isPresent(this.translationLoadedSub)) {
      this.translationLoadedSub.unsubscribe();
      this.translationLoadedSub = undefined;
    }
  }

  ngOnDestroy(): void {
    this._dispose();
  }
}

这是相应的plunkr:https://plnkr.co/edit/VMqCvX?p=preview.

点赞