What would be the optimal structure to use in Angular 2+ component so as to utilize the power of rxjs switchMap() in a back-end call via a service?
Notes:
- We have a nested component firing a custom "fetch" event (so
fromEvent(myBtn2.nativeElement, 'fetch').pipe(...);
is not firing, see comment (1), so we workaround it withSubject
. If there's a way harnessfetch
withfromEvent()
, we could spare the use ofSubject
)
Sample implementation in StackBlitz here
app.component.html
<app-inner #myBtn1 (fetch)="onFetch1($event)" [data]="data"></app-inner>
<app-inner #myBtn2 (fetch)="onFetch2($event)" [data]="data"></app-inner>
app.component.ts
@Component({...})
export class AppComponent implements {
@ViewChild('myBtn2', { read: ElementRef }) myBtn2: ElementRef;
public data = 0;
private BTN = { GET: new Subject() };
private subs = new Subscription();
constructor (private _ds: DataService) {}
public ngOnInit() {
this.setBtnLogic();
}
public onFetch1(ev) {
this.subs.add(
this._ds.getData().subscribe(res => {
this.data = res;
console.log('<<<', res); // <-- logs 10 times
})
);
}
public onFetch2(ev) {
this.BTN.GET.next(ev);
}
public setBtnLogic(ev?) {
// fromEvent(this.myBtn2.nativeElement, 'fetch') // <-- (1) this is not working
this.BTN.GET
.pipe(
switchMap(p => this._ds.getData()),
tap(data => this.data = data),
tap(res => console.log('<<< observable ', res)), // <-- logs only the last response
).subscribe();
}
// unsubscribes in ngOnDestroy() ...
}