When to use asObservable() in rxjs?

When to use Subject.prototype.asObservable() The purpose of this is to prevent leaking the “observer side” of the Subject out of an API. Basically to prevent a leaky abstraction when you don’t want people to be able to “next” into the resulting observable. Example (NOTE: This really isn’t how you should make a data source like … Read more

What is “callback hell” and how and why does RX solve it?

1) What is a “callback hell” for someone who does not know javascript and node.js ? This other question has some examples of Javascript callback hell: How to avoid long nesting of asynchronous functions in Node.js The problem in Javascript is that the only way to “freeze” a computation and have the “rest of it” … Read more

How can I close a dropdown on click outside?

You can use (document:click) event: @Component({ host: { ‘(document:click)’: ‘onClick($event)’, }, }) class SomeComponent() { constructor(private _eref: ElementRef) { } onClick(event) { if (!this._eref.nativeElement.contains(event.target)) // or some similar check doSomething(); } } Another approach is to create custom event as a directive. Check out these posts by Ben Nadel: tracking-click-events-outside-the-current-component selectors-and-outputs-can-have-the-same-name DirectiveMetadata Host Binding

Why do we need to use flatMap?

[‘a’,’b’,’c’].flatMap(function(e) { return [e, e+ ‘x’, e+ ‘y’, e+ ‘z’ ]; }); //[‘a’, ‘ax’, ‘ay’, ‘az’, ‘b’, ‘bx’, ‘by’, ‘bz’, ‘c’, ‘cx’, ‘cy’, ‘cz’] [‘a’,’b’,’c’].map(function(e) { return [e, e+ ‘x’, e+ ‘y’, e+ ‘z’ ]; }); //[Array[4], Array[4], Array[4]] You use flatMap when you have an Observable whose results are more Observables. If you have … Read more

Angular 4 Interceptor retry requests after token refresh

My final solution. Works with parallel requests. UPDATE: The code updated with Angular 9 / RxJS 6, error handling and fix looping when refreshToken fails import { HttpRequest, HttpHandler, HttpInterceptor, HTTP_INTERCEPTORS } from “@angular/common/http”; import { Injector } from “@angular/core”; import { Router } from “@angular/router”; import { Subject, Observable, throwError } from “rxjs”; import … Read more

take(1) vs first()

Operators first() and take(1) aren’t the same. The first() operator takes an optional predicate function and emits an error notification when no value matched when the source completed. For example this will emit an error: import { EMPTY, range } from ‘rxjs’; import { first, take } from ‘rxjs/operators’; EMPTY.pipe( first(), ).subscribe(console.log, err => console.log(‘Error’, … Read more