我看了一下,但似乎没有关于Angular2中服务之间共享数据的材料。我有两个@Injectable()服务,其中一个是广播数据的Singleton。在另一个服务中,我有一个代码,可以在Web音轨播放时更新名为progress的变量:
import { SharedService } from '../shared.service';
...
@Injectable()
export class WebAudioTrack implements IAudioTrack {
public _progress: number = 0;
...
constructor(public src: string, @Optional() public preload: string = 'none', @Optional() private ctx: AudioContext = undefined ) {
// audio context not needed for now
// this.ctx = this.ctx || new AudioContext();
this.createAudio();
}
private onTimeUpdate(e: Event) {
if (this.isPlaying && this.audio.currentTime > 0) {
# I want to do something like SharedService.setProgress(this.audio.currentTime) here
this._progress = this.audio.currentTime;
this._completed = this.audio.duration > 0 ? Math.trunc (this.audio.currentTime / this.audio.duration * 100)/100 : 0;
}
}
我正在寻找一种方法将上面代码中的_progress变量广播到另一个名为SharedService的@Injectable。我甚至不需要在上面的代码中设置BehaviorSubject,因为每次onTimeUpdate触发时我都应该能够执行像SharedService.setProgress(time)这样的操作。
问题是,如何将SharedService添加到上面的代码中?当我尝试将它添加到构造函数时,它会抱怨因为有新的WebTrackAudio(变量,变量)和#34;的调用。这里的其他服务代码不完整,可能会有些混乱:
@Injectable()
export class SharedService {
progress: number;
setProgress(progress: number) {
console.log(progress);
this.progress = progress;
}
getProgress() {
return this._webTrack._progress;
}
}
谢谢!
当我更新第一个服务中的构造函数以包含SharedService时:
constructor(public src: string, @Optional() public preload: string = 'none', @Optional() private ctx: AudioContext = undefined, public sharedService: SharedService ) {
// audio context not needed for now
// this.ctx = this.ctx || new AudioContext();
this.createAudio();
}
我收到以下错误:
打字稿错误
提供的参数与呼叫目标的任何签名都不匹配。
... / SRC /应用/离子音频/离子-音频providers.ts
create(track:ITrackConstraint){
让audioTrack = new WebAudioTrack(track.src,track.preload);
Object.assign(audioTrack,track);
答案 0 :(得分:2)
import { SharedService } from '../shared.service';
...
@Injectable()
export class WebAudioTrack implements IAudioTrack {
public _progress: number = 0;
...
constructor(private sharedService:SharedService) {}
private onTimeUpdate(e: Event) {
if (this.isPlaying && this.audio.currentTime > 0) {
# I want to do something like this.sharedService.setProgress(this.audio.currentTime) here
this._progress = this.audio.currentTime;
this._completed = this.audio.duration > 0 ? Math.trunc (this.audio.currentTime / this.audio.duration * 100)/100 : 0;
}
}
确保提供两种服务,如
@NgModule({
...,
providers: [WebAudioTrack, SharedService],
})
export class AppModule {}