我有一个组件,用于显示特定视频的标题和艺术家。当我在我的服务中调用 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>
每次调用 playNext() 函数时,组件内的 subscribe 函数都会在控制台输出这个信息,所以我知道它是正确变化的,只是用户界面没有更新。
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,但我听说这可能不是最好的方法,老实说,它感觉有点hacky。
NgZone.isInAngularZone()
应该会给你答案。 - yurzui