我有一个组件,显示一个特定的视频标题和艺术家。当我在服务中调用playNext()时,它应该用新数据更新标题和艺术家。我做了一个控制台.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>
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,但我听说这可能不是最好的方法,老实说,这感觉有点黑客。