Search code examples
angularhttpangular2-pipe

How to load JSON from a pipe?


I have a service that's loading a JSON file and using that service in a custom pipe:

import { Pipe, PipeTransform } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { LanguageLoadService } from '../../services/language-load/language-load.service';

@Pipe({name: 'langAsset'})
export class LangAsset implements PipeTransform {

  constructor(private languageService: LanguageLoadService) {

  }

  transform(textKey: string): Observable<any> {
    return new Observable(observer => {
      this.languageService.loadLanguage("en-US").subscribe((langData) => {
        observer.next(langData[textKey] ? langData[textKey] : 'Error');
      })
    });
  }
}

And on the template:

<p>{{'test' | langAsset | async }}</p>

But it seems that transform runs before the service finishes loading the JSON, as the result is [object Object] on the page, and console.log prints it out fine when it logs from inside the loadLanguage subscribe. How can I get this to rerun, by returning an observable instead of a string in the transform function? I know I have to use AsyncPipe, but I'm unsure how to go about this.


Solution

  • Try using <p>{{'test' | langAsset | async | json}}</p>

    It is a nested Json object which the html tag cannot understand the json pipe is equivalent to stringfy Json pipe