Slyke
Slyke

Reputation: 134

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.

Upvotes: 4

Views: 2660

Answers (2)

Rahul Singh
Rahul Singh

Reputation: 19622

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

Upvotes: 4

Brendan Whiting
Brendan Whiting

Reputation: 494

I’m not 100% sure but I think your pipe might be returning an Observable wrapping and Observable. Try piping in twice through the async pipe. Or tell Typescript explicitly what kind of Observable your transform function returns instead of Observable so that it will yell at you if that’s not true. If it is an Observable of an Observable you should use flatMap.

Upvotes: 0

Related Questions