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.
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.
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.
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.
Async pipe is an example of an Impure pipe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With