Filter all 'null' values from an Observable<T>
Add a filter operator to your observable chain. You can filter nulls explicitly or just check that your user is truthy - you will have to make that call depending on your needs.
Filtering out null users only:
public currentUser = this.currentUserSubject
.asObservable()
.filter(user => user !== null)
.distinctUntilChanged();
Another way to check the value exists:
public currentUser = this.currentUserSubject
.asObservable()
.filter<User>(Boolean)
.distinctUntilChanged();
with rxjs@6
and typescript the recommended (readable/maintainable) way is to define the following type guard:
export function isNonNull<T>(value: T): value is NonNullable<T> {
return value != null;
}
and augment a subject with pipe
and filter
:
subject.pipe(filter(isNonNull))