How can i use async pipe to handle click or other user event ?


Almost all of the tutorials related to async pipe is related to loading data from api. But there is another thing you can do with it. Lets say you have a button which sends some data to api. The imperative code would look something like this





@Component({
selector: 'app-root',
template: `<button (click)="click()"></button>`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'test';

click() {
this.apiService.send()
.pipe(take(1)) // complete upon first emission
.subscribe(() => {})
}
}




That is, its creating a new subscription every click and completes. And if you forget to use take(1) operator you would be creating multiple subscriptions. The clean way of doing this would be to create an subject and subscribe with async pipe.





@Component({
selector: 'app-root',
template: `<ng-container *ngIf="clickStream$|async"></ng-container> <button (click)="this.clickStream.next(true)"></button>`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'test';

clickStream = new Subject();
clickStream$ = this.clickStream.asObservable()
.pipe( concatMap(() => this.apiService.send()) )

}




This snippet of code doesn't create new subscription per every click. The subscription for click event is removed when the component is destroyed.


Share:

0 comments:

Post a Comment