gpt4 book ai didi

Angular 6 String Interpolation 不使用 .subscribe() 内的值更新

转载 作者:行者123 更新时间:2023-12-03 20:16:44 25 4
gpt4 key购买 nike

我有一个组件可以显示特定视频的标题和艺术家。当我在我的服务中调用 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&nbsp;&nbsp;<button class="btn btn-secondary">+ Subscribe</button></div>
</div>

每次调用 playNext() 时,组件订阅函数内的控制台日志都会显示这一点,所以我知道它正在正确更改,只是 UI 没有更新。
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。

最佳答案

可能这可以帮助:

@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,
private changeDetector: ChangeDetectorRef
) { }

ngOnInit() {
this.nowPlaying = this.videoService.getNowPlaying();
console.log('nowPlayingComponent');
this.nowPlaying.subscribe(v => {
this.video = v;
this.changeDetector.detectChanges();
console.log('nowPlaying:', this.video);
});
}
}

关于Angular 6 String Interpolation 不使用 .subscribe() 内的值更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52324855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com