我有一个包含主题和可观察的歌曲设置列表(显示为| async
在视图中),现在我想从列表中删除一首歌曲,请执行一些操作filter()
并打电话next()
就此主题而言。
如何以及在哪里进行过滤?现在我正在做getValue()
关于主题并将其传递给next()
关于,好吧,主题。这似乎是错误的和循环的。
我还尝试订阅主题并以这种方式获取数据,过滤它并调用next()
inside subscribe()
,但我遇到了 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();
}
}
我建议您在组件上创建新属性,您将在其中最后存储状态。 (这里理解歌曲数组)。
总是更好地通过代表您的状态(或存储)的内部属性和具有同步应用程序其余部分(通过可观察/事件)的角色的另一个属性来概念化您的代码。
另一个技巧是按模型强类型化您的代码。将更容易调试和维护。
然后你只需根据你的逻辑更新它,然后更新你的主题
export interface SongModel {
id: number;
title: string;
artiste: string;
}
export class ArtistComponent implements OnInit {
private repertoire$ : Observable<SongModel[]>;
private repertoireSubject: BehaviorSubject<SongModel[]>;
//Array of song, should be same type than repertoireSubject.
private songs: SongModel[];
constructor(
private route: ActivatedRoute,
private service: ArtistService
) {
//We push all actual references.
this.getRepertoire().subscribe(
songs => {
this.songs = songs;
this.repertoireSubject.next(this.songs);
}
);
}
ngOnInit() {
//Because is suject of array, you should init by empty array.
this.repertoireSubject = new BehaviorSubject<SongModel[]>([]);
this.repertoire$ = this.repertoireSubject.asObservable();
}
getRepertoire() {
return this.route.paramMap
.switchMap((params: ParamMap) =>
this.service.fetchRepertoire(params.get('id')));
}
//THIS IS WHERE I'M HAVING TROUBLE
delete(id: number): void {
// Update your array referencial.
this.songs = this.songs.filter(songs => songs.id !== id);
// Notify rest of your application.
this.repertoireSubject.next(this.songs);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)