angular(4/0)

Organize subscription chains with pipes

Often, two or more observables depend upon one another for execution. This can lead to chained subscriptions. Take this real-world example: this.openInvalidPeriodDialog$(dialog).subscribe(dialog => { dialog.afterClosed().subscribe(jumpToLatestPeriod => { if (jumpToLatestPeriod) { this.periodService.getLatestPeriod().subscribe(latestPeriod => { this.analysisService.getPreliminaryPeriodId$(federalReserveId, analysisId, latestPeriod.id) .subscribe(periodId => this.sessionService.setQualitativePeriod(periodId ?? latestPeriod.id)) }); } }); }); The multiple subscribes() might be written in a more descriptive chain with a pipe and use of switchMap() and filter(). this.openInvalidPeriodDialog$(rejectionDialog) .pipe( switchMap(invalidPeriodDialog => invalidPeriodDialog.afterClosed()), filter(jumpToLatestPeriod => jumpToLatestPeriod), switchMap(() => this.…

Simplify loop with iterator swap

When operating on two or more collections you may encounter loops that filter one collection by another. Say we have a collection of dinners and a collection of ingredients. We want to find out, given our ingredients, which dinners are using at least one ingredient. We might write our filter like this: const dinners = this.getDinnerRecipes(); const ingredients = this.getIngredients(); const dinnerIds = ingredients.map(i => i.dinnerId); const dinnerOptions = dinners.filter(dinner => { if (dinnerIds.…

Angular maxims

This is an incomplete list of maxims I’ve gleaned while working on Angular/RxJS development. favor identifier over index simplify loop with iterator swap smart components observe state over input organize subscription chains with pipes one subscription per resource distinguish series and one time observables 💬 RxJS has a reputation for being complex, hard to understand, and hard to use. A deserved reputation, to be honest. I’ve used RxJS in a project to great effect, it made an impossible problem possible, but getting your head around it isn’t trivial.…

Favor identifier over index

If there are several arrays of data retrieved from different service calls it can be tempting to iterate over them all by index. const columnsFirst = this.dataService.getFirstData(); const columnsSecond = this.dataService.getSecondData(); columnsTotal = []; for (var i = 0; i < columnsFirst.length(); i++) { const total = columnsFirst[i].value + columnsSecond[i].value; columnsTotal.append(total); } return columnsTotal; Iteration by index is prone to many errors, however. The order of each column array must match, their lengths must equal (although this can be overcome with a null check), and it’s not clear to other developers why there’s a hard dependency between these arrays without further investigation.…