Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  8] [ 4]  / answers: 1 / hits: 44359  / 7 Years ago, mon, march 27, 2017, 12:00:00

I have a service with a subject:



@Injectable() export class UserService() {
private currentUserSubject = new BehaviorSubject<User>(null);
public currentUser = this.currentUserSubject.asObservable().distinctUntilChanged();

... // emitting new User
}


Have a component I inject this service into and subscribing on 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> to filter all null values and get into subscribe only when User is actually loaded.


More From » angular

 Answers
6

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();

[#58369] Friday, March 24, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
haleeg

Total Points: 703
Total Questions: 100
Total Answers: 98

Location: Dominica
Member since Sat, Nov 5, 2022
2 Years ago
;