我有一个组件,可以显示特定视频的标题和艺术家。当我在服务中调用playNext()时,应该使用新数据更新标题和艺术家。我执行console.log,可以验证订阅是否有效。每次调用playNext()时,我都会获得一个更新的值,但是模板中的值不会被更新。仅在第一次时正确显示。我想念什么吗?
这是我的组件代码
@Component({
selector: 'ntv-now-playing',
templateUrl: './now-playing.component.html',
styleUrls: ['./now-playing.component.css']
})
export class NowPlayingComponent implements OnInit {
nowPlaying: Observable<Video>;
video: Video;
constructor(private videoService: VideoPlayerService) { }
ngOnInit() {
this.nowPlaying = this.videoService.getNowPlaying();
console.log('nowPlayingComponent');
this.nowPlaying.subscribe(v => {
this.video = v;
console.log('nowPlaying:', this.video);
});
}
}
在我的服务中,我这样做:为简洁起见,我删除了一些工作代码。
@Injectable()
export class VideoPlayerService {
...
nowPlayingChanged = new Subject<Video>();
...
private nowPlaying: Video;
constructor(private db: AngularFirestore) {}
...
getNowPlaying(): Observable<Video> {
return this.nowPlayingChanged;
}
playNext(vIdx: number, lastIdx: number) {
console.log('playNext()');
this.nowPlaying = this.videos[vIdx];
console.log(this.nowPlaying);
this.nowPlayingChanged.next(this.nowPlaying);
}
}
我的模板具有以下内容:
<div class="video-info">
<h5>{{video?.title}} - {{video?.artist}}</h5>
<div>Channel Info <button class="btn btn-secondary">+ Subscribe</button></div>
</div>
组件的subscribe函数中的控制台日志在每次调用playNext()时都会显示此信息,因此我知道它的更改正确,只是用户界面没有更新。
nowPlaying: {artist: "Alan Walker", duration: "3:32", startTime: Timestamp, thumbnailPath: "https://i.ytimg.com/vi/60ItHLz5WEA/hqdefault.jpg", title: "Faded", …}
nowPlaying: {artist: "Deadmau5", duration: "3:37", thumbnailPath: "https://i.ytimg.com/vi/UG3sfZKtCQI/hqdefault.jpg", title: "Monophobia", videoId: "UG3sfZKtCQI"}
nowPlaying: {artist: "Steve Aoki", duration: "59:55", thumbnailPath: "https://i.ytimg.com/vi/sR3w1P2nPH8/hqdefault.jpg", title: "Tomorrowland", videoId: "x9ZkC3OgI78"}
video-player.component.ts:69
任何建议都值得赞赏。我见过有人在使用ngZone,但我听说这可能不是最好的方法,说实话,这感觉有些怪异。