Angular 4 - 服务数据不是持久的

时间:2017-11-05 16:05:55

标签: html5 angular typescript html5-audio angular-services

我在找出错误的地方时遇到了一些麻烦,并且非常感谢您对此有所帮助。

我有一个组件:AudioComponent,它将html5标记捕获为@ViewChild,然后使用服务注册自己:AudioService

以下是AudioComponent

/* audio.component.ts */
import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { IAudioOptions } from './audio-options';

export const defaultOptions: IAudioOptions = {
  controls: true,
  autoplay: false,
  loop: false,
  volume: 1.0,
  startPosition: 0.0,
  preload: "metadata",
  muted: false
};

@Component({
  selector: 'ng-audio',
  templateUrl: './audio.component.html',
  styleUrls: ['./audio.component.css']
})
export class AudioComponent implements OnInit {
  @Input() src: any;
  @Input() options: any = defaultOptions;
  @Input() register: any;

  @ViewChild('audio') player: any;

  constructor() { }

  ngOnInit() {
    if (this.register) {
      console.log("registering");
      console.log(this.register(this));
    }
  }

  play() {
    this.player.nativeElement.play();
  }

}

AudioService

/* audio.service.ts */
import { Injectable } from '@angular/core';
import { AudioComponent } from './audio/audio.component';

@Injectable()
export class AudioService {
  private players: AudioComponent[];

  constructor() { }

  register(player: AudioComponent) {
    console.log("player registered");
    if (this.players) {
      this.players.push(player);
    }
    else {
      console.log("initializing service");
      this.players = [];
      this.players.push(player);
    }
    return this.players;
  }

  getPlayers(): string[] {
    var out: string[];
    for (let i = 0; i < this.players.length; i++) {
      out.push(this.players[i].src);
    }
    return out;
  }

}

我在我的ng-audio文件中实例化了两个app.component.html组件:

<!-- register refers to the AudioService.register function -->
<ng-audio [src]="src" [register]="register"></ng-audio>
<ng-audio [src]="src2" [register]="register"></ng-audio>

当我加载页面时,音频播放器本身会出现。

令人费解的是,我将以下内容登录到控制台:

- registering
- player registered
- initializing service
- [AudioComponent]
- registering
- player registered
- initializing service // <- this should only happen the first time!
- [AudioComponent]     // <- and this should now contain two elements!

由于某种原因,players: AudioComponent[]的{​​{1}}属性不会持续存在。因此,每次调用AudioService时,就像我在一个全新的register()实例上调用它一样!

再一次,任何帮助将不胜感激。如果我能解决这个问题,我会发布更新。

编辑:我已经包含了我的AudioServiceapp.module.ts个文件,以防我错过了将服务设置为提供商的情况。

app.component.ts

AppModule

/* app.module.ts */ import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { AudioComponent } from './audio/audio.component'; import { AudioService } from './audio.service'; @NgModule({ declarations: [ AppComponent, AudioComponent ], imports: [ BrowserModule ], exports: [AudioComponent], providers: [AudioService], bootstrap: [AppComponent] }) export class AppModule { }

AppComponent

0 个答案:

没有答案
相关问题