6

I am creating my custom pipe, culture which performs some async localdb/http request to return data from the server. Let's look at the following:

{{ 'hello' | culture:'es-mx' }}

I need this to be Hola, but I want this to be rendered async. The PipeTransform interface provides me with transform(value: any, ...args: any[]): any interface. How can I implement it async? Is this something doable?

The answers in this question, for example suggest the async pipe, followed by a filter/sort to achieve this to be actively listening to an array changes and filter, but that seems performance heavy because there are many pipes in my application.

I would like to implement something like this:

 transform(value: any, ...args: any[]): any {

        operation.subscribe(result => {
            // set the pipe value from here...
        })


 }
tika
  • 7,135
  • 3
  • 51
  • 82
  • See https://stackoverflow.com/a/48900163/3731501 as a reference – Estus Flask Mar 13 '18 at 15:46
  • You can return an observable, so that it would work with the async pipe (see [this stackblitz](https://stackblitz.com/edit/angular-pipe-psni5j?file=app%2Fcustom-text.pipe.ts)). I don't know if there are major drawbacks to that suggestion, except for requiring the pipe to be used with async. – ConnorsFan Mar 13 '18 at 15:58

1 Answers1

0

Yes, you can return an Observable or Promise from a Pipe. Angular recommends caching the data retrieved in a pipe when it's performing an expensive operation because of frequent change detection cycles. This caching example, linked above is a perfect example of what you want to do. It also describes the pure: false property of the @Pipe decorator you will want to use in this instance (since I'm assuming the URL for the http get request will change as the text to translate changes).

Carlo Bos
  • 3,105
  • 2
  • 16
  • 29