Filter out all "null" values from observable <T>
I have a service with a theme:
@Injectable() export class UserService() {
private currentUserSubject = new BehaviorSubject<User>(null);
public currentUser = this.currentUserSubject.asObservable().distinctUntilChanged();
... // emitting new User
}
Have a component that I insert this service and subscribe to updates:
@Component() export class UserComponent {
constructor(private userService: UserService) {
this.userService.currentUser
.subscribe((user) => {
// I want to see not null value here
})
}
}
I want to apply something to Observable<User>
in order to filter out all null values and only enter the subscription on download User
.
+3
source to share
2 answers
Add a filter operator to your observable chain. You can filter the zeros explicitly, or just check that your user is truthful - you will have to make this call depending on your needs.
Filtering only null users:
public currentUser = this.currentUserSubject
.asObservable()
.filter(user => user !== null)
.distinctUntilChanged();
+10
source to share