Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async pipe with a method call in angular 4 calls infinitely

I need to provide select UI element with dynamic options for which I have a method that returns an observable based on the Inputs

TypeScript (Component class)

getCars(type : string, engine : string) : Observable<Cars>{
    return this.carService.getCars(type,engine);
} 

In the HTML I make my element call this method for data

Html (Template file)

<ng-select [items]="getCars(type,engine) | async"
    bindLabel="value"
    bindValue="id"
</ng-select>

but this results in service being called infinitely. I do not want to use ngOnInit as I need the observable to be dynamically assigned

I'm using this UI element for select

like image 793
Mahi Tej Gvp Avatar asked Apr 15 '18 15:04

Mahi Tej Gvp


2 Answers

this is the expected behavior, and how angular change detection works, it's not a good idea to call method from the view and use a property instead

this.cars = getCars(type,engine)
like image 79
Fateh Mohamed Avatar answered Sep 28 '22 06:09

Fateh Mohamed


I achived it by calling this method to change the observable variable

in Component

    car$:Observable<cars> 
getCars(type : string, engine : string) {
    this.car$=this.carService.getCars(type,engine);
} 

in Template

<ng-select [items]="car$ | async"
    (focus)="getCars(type,engine)"
    bindLabel="value"
    bindValue="id"
</ng-select>
like image 25
Mahi Tej Gvp Avatar answered Sep 28 '22 07:09

Mahi Tej Gvp