【发布时间】:2017-06-29 23:31:48
【问题描述】:
我环顾四周,但似乎没有关于在 Angular2 中的服务之间共享数据的材料。我有两个 @Injectable() 服务,其中一个是广播数据的单例。在另一项服务中,我的代码会在播放网络音轨时更新名为 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 添加到上面的代码中?当我尝试将它添加到构造函数时,它会抱怨,因为有对“new WebTrackAudio(变量,变量)”的调用。这是另一个不完整的服务代码,可能会有些混乱:
@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/app/ionic-audio/ionic-audio-providers.ts
创建(轨道:ITrackConstraint){
让 audioTrack = new WebAudioTrack(track.src, track.preload);
Object.assign(audioTrack, track);
【问题讨论】:
-
我肯定能找到问题的核心,您可以删除 2/3 的代码。我发现所有的噪音实际上是什么问题让我很困惑。要在服务之间共享数据,只要不导致循环依赖,您只需将一个服务注入另一个服务即可。
-
“添加到构造函数”是什么意思?如果它是一项服务,为什么需要致电
new WebTrackAudio(variable, variable)? -
我实际上已经删除了大约 90% 的代码(你可以看到 ...s)。我想这不是服务?之后怎么样了?我仍然被 angular2 弄湿了
-
这不是单例服务,但我认为它仍然是一项服务......如果我错了,请纠正我
-
向什么添加服务?也许您的意思是将服务注入包含代码
new WebAudioTrack(track.src, track.preload);的类,然后像new WebAudioTrack(track.src, track.preload, sharedService);一样传递服务。无法自动将服务传递给您使用new创建的类实例。