Reputation: 37
I have a film
object and it has a genre
property.
I want to get films by genre at runtime in custom dropdown FormControl
.
So I define new BehaviourSubject(<int>) genre
and if it will change at runtime, get value in ngOnChanges()
method. And after that it hits API. But I want to check genre value before that. For example if genre.getValue = 0
don't call the API.
Sample code is below. How can I check value?
private _genre;
private selectedGenre = new BehaviorSubject(0);
@Input()
set genre(value: any) {
this._genre = value;
this.selectedGenre.next(this._genre);
}
films: any[];
ngOnInit() {
this.selectedGenre.distinctUntilChanged().combineLatest(
this.selectedGenre.distinctUntilChanged(), (_genre) => {
return {
genre: _genre
}
}
)
.switchMap(t => this.service.getFilmsByGenre(genre))
.subscribe(result => {
if (result) this.films = result;
});
}
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
if (changes['genre']) {
this.films = null;
this.filmCtrl.setValue(null);
this.selectedGenre.next(changes['genre'].currentValue || 0);
}
}
Upvotes: 0
Views: 50
Reputation: 608
You can use filter to subscribe to only those values which you need to call API.
this.selectedGenre.distinctUntilChanged().combineLatest(
this.selectedGenre.distinctUntilChanged(), (_genre) => {
return {
genre: _genre
}
}
)
.filter(genre=>genre.getValue!==0)
.switchMap(genre => this.service.getFilmsByGenre(genre))
.subscribe(result => {
if (result) this.films = result;
});
Upvotes: 1