【发布时间】:2018-03-20 13:25:12
【问题描述】:
我有一个包含主题和可观察的歌曲列表(显示为| async),现在我想从列表中删除一首歌曲,做一些filter() 并在主题上调用next()。
我如何过滤以及在哪里过滤?现在我正在对主题执行 getValue() 并将其传递给主题上的 next()。这似乎是错误的和循环的。
我也尝试订阅主题并以这种方式获取数据,过滤它并在subscribe() 中调用next(),但我得到了一个 RangeError。
我可以通过存储所有已删除的 id 来过滤 Observable。然后,主题的列表会因为删除了那里的歌曲而变得不同步,而且每个观察者都必须拥有似乎很可笑的已删除 ID 的列表。我正在迅速变老和精神。请帮我上网:(
export class ArtistComponent implements OnInit {
private repertoire$;
private repertoireSubject;
constructor(
private route: ActivatedRoute,
private service: ArtistService
) {
this.getRepertoire().subscribe(
songs => this.repertoireSubject.next(songs)
);
}
getRepertoire() {
return this.route.paramMap
.switchMap((params: ParamMap) =>
this.service.fetchRepertoire(params.get('id')));
}
//THIS IS WHERE I'M HAVING TROUBLE
delete(id): void {
this.repertoireSubject.next(
this.repertoireSubject.getValue().filter(song => (song.id !== id))
);
// TODO remove song from repertoire API
}
ngOnInit() {
this.repertoireSubject = new BehaviorSubject<any>(null);
this.repertoire$ = this.repertoireSubject.asObservable();
}
}
【问题讨论】:
-
是的,你应该有一些歌曲的数组,否则会变得非常困难。
-
@trichetriche 那么如何解决删除歌曲后主题不同步的问题?我在想一定有一些我还没有弄清楚的过滤方式
-
好的,我正在回答,请稍等
标签: angular rxjs observable rxjs5 subject-observer