Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise in Pipe transform

I don't want to use "| async pipe" because I don't want to get data for every component. My transform function below:

 transform(key: string, ...args) {
  this.storage.get("dictionary").then((dict) => {         
   var translated = dict[key] || "noResource";
   console.log("key = "+key + ", value = "+translated);
   return translated; 
  });  
}

I can get key and values but value does not rendered. I tried ngZone but not working.

like image 956
Berk Akkerman Avatar asked Feb 06 '18 07:02

Berk Akkerman


People also ask

Why promises are used in Angular?

Promises in Angular provide an easy way to execute asynchronous functions that use callbacks, while emitting and completing (resolving or rejecting) one value at a time. When using an Angular Promise, you are enabled to emit a single event from the API.

What is sync and async pipe in Angular?

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

Can Angular pipe return Observable?

Angular expects pipes to be synchronous. They should return a resolved value, not a Promise or an Observable . To use a pipe that returns an unresolved value, you can use Angular's async pipe. If that's not an option, you can resolve the asynchronous value inside the pipe if you make it impure, as I describe below.

Is async a pure pipe?

Async pipe is an example of an Impure pipe.


1 Answers

I don't understand why you don't want to use the only "buildin" pipe that matches your case.

says your pipe is :

 @Pipe({name: 'mypipe'})
    export class MyPipe implements PipeTransform
    {
        transform(key: string, ...args) {
            // watch out you missed the return statement !!
            -->return<-- this.storage.get("dictionary").then((dict) => {         
            var translated = dict[key] || "noResource";
            console.log("key = "+key + ", value = "+translated);
            return translated; 
        });  
    }

the in your template you could just use

{{ 'mykey' | mypipe | async }}

If you don't want to use async pipe you will be forced to mimic is logic who is already dead simple and bug proof. No gain for you.

like image 89
Pierre Mallet Avatar answered Sep 20 '22 12:09

Pierre Mallet