How can I prevent the Angular async pipe from making frequent server calls when no results come back?

后端 未结 2 1297
清酒与你
清酒与你 2021-02-08 03:42

I\'m using the async pipe in an ngFor to watch an Observable. The Observable is created by a service that hits my server, and on load time when ngFor loop is enume

2条回答
  •  猫巷女王i
    2021-02-08 04:02

    Angular will check for changes when an even occurs. It means it will call the variables present in the template to see if their result changed or not.

    If at each call you return a different object or array (even if the content is the same) angular will consider the content to have changed and refresh the template (resubscribing from the async pipe).

    In your case you are calling "persons" which will return every time a different observable.

    one solution is to affect the observable to a local variable and then to use this local variable in the template. Something like that:

    class myComponent {
    public $persons:Observable;
    constructor(){
    this.$persons = this.$getPersons();
    }
    
    private $getPersons():Observable{
    return this.personService.list();
    }
    }
    

    And your template

  • {{person.id}}
  • Another way is to use the decorator @Memoize which will cache the result of the method and return the same object once for all.

    https://www.npmjs.com/package/typescript-memoize

    Keep your code and just add the decorator it to your getter:

    @Memoize()
    get persons: Observable {
        return this.personService.list();
    }
    

    Bonus: You probably want to cache the last value received from your service (reason why you have the "if condition"). You should consider using a replay (publishLast or publishReplay)

提交回复
热议问题