Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to avoid multiple executions of a impure pipe in angular 2?

Hi I am using Angular 2 pipe to return the keys of object, it is an impure pipe and It is being executed multiple times which is blocking some other script, how can I avoid multiple executions of the impure pipes? my code is as follows :

 import {Pipe,PipeTransform} from '@angular/core';
    @Pipe({ name: 'NgforObjPipe', pure: true })
    export class NgforObjPipe implements PipeTransform {
        transform(value, args:string[]):any {
        let keys = [];
        for (let key in value) {
            keys.push({key: key, value: value[key]});
        }
        console.log('pipeeeeeeeeeeeeeee', keys);
        return keys;
        }
    }
like image 942
Shiva Nayak Dharavath Avatar asked Jul 25 '17 04:07

Shiva Nayak Dharavath


People also ask

Which of the following are reasons to use impure pipes carefully in Angular?

Impure pipes are required because angular ignores changes to composite objects. Impure pipes execute every time angular detects any changes regardless of the change in the input value. It uses the impure function.

How do you specify impure pipes using pure property?

From the above code, the isPure method will check whether a pipe is pure or impure by looking at the pure property in @Pipe decorator. For impure pipes Angular calls the transform method on every change detection. For any input change to the pure pipe, it will call transform function.

Why Async pipe is impure?

Because of the way Promise s work, Angular's async pipe has to be impure (meaning that it can return different outputs without any change in input). The transform method on Pipe s is synchronous, so when an async pipe gets a Promise , the pipe adds a callback to the Promise and returns null.

What does .pipe do in Angular?

Pipes let you combine multiple functions into a single function. The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence. Do you have an example?


1 Answers

There is no way to prevent that. That's what an impure pipe is for.

What you can do is, to ensure that as little work is done inside the the transform() method as possible, for example by caching results and only recalculate when the passed value has actually changed.

You can also use Object.keys() to get more efficient code. See also How to iterate [object object] using *ngFor in Angular 2

ChangeDetectionStrategy.OnPush can be used to reduce the number of times change detection is run, to minimize the number of calls to the pipe.

like image 166
Günter Zöchbauer Avatar answered Oct 11 '22 04:10

Günter Zöchbauer