使数据存储在提供程序中

时间:2016-06-25 16:38:16

标签: angular typescript ionic2 ionic3

我在Ionic 2中使用模态来做一些类似于音乐播放器的东西。在这个模态中,我设置了几个我想要保留的变量,即使模态关闭并创建了一个新模态。为了保存数据,我将其存储在服务中,就像在Angular 1中一样。

我的页面组件:

this.playerService.setRelease(this.params.get('release'));
console.log(this.playerService.getStoredRelease()); // This works right after it is being stored.

我的服务:

setRelease(release) {
  this.release = release;
}

getStoredRelease() {
  return this.release;
}

这一切都是在一个模态中完成的。一旦我调用this.viewCtrl.dismiss();并使用Ionic的

重新打开模态
openModal(release) {
  let modal = Modal.create(ModalsContentPage, release);
  this.navController.present(modal);
}

我调用console.log(this.playerService.getStoredRelease());在设置它之前它是未定义的。如何将服务保存到数据的位置。我应该用别的吗?

player.ts

import {Component, Renderer} from '@angular/core';
import {NavController, Platform, NavParams, ViewController} from 'ionic-angular';
import {PlayerService} from '../../providers/player-service/player-service';
import {ConnectService} from '../../providers/connect-service/connect-service';
declare var $: JQueryStatic;

@Component({
  templateUrl: './build/pages/player/player.html',
  providers: [PlayerService, ConnectService]
})

export class ModalsContentPage {
  release;
  art;
  public song: any;
  artists;
  title;
  private time: any;
  private pos: any;
  public counter: any;

  constructor(
    public platform: Platform,
    public params: NavParams,
    public viewCtrl: ViewController,
    public playerService: PlayerService,
    public connectService: ConnectService
  ) {
    this.time = {};
    this.time.percent = 0;
    this.playerService.getStoredRelease();
    console.log(this.params.get('release'));
      if (this.playerService.getStoredRelease() === this.params.get('release')) {
        console.log('wew lad i did it');
      } else {
      this.playerService.setRelease(this.params.get('release'));
      console.log(this.playerService.getStoredRelease());
      this.release = this.params.get('release');
      this.fetchSong(this.release._id);
      this.art = this.release.artwork_url;
    }
  }

  fetchSong(id) {
    this.connectService.loadSongs(id)
      .then(data => {
        this.song = data[0];
        //this.songs = data ##The song var will just be at the index specified. 
        this.artists = this.song.artistsTitle;
        this.title = this.song.title;
        this.init();
      })
  }

  init() {
    $('.range-slider').on("touchstart", () => this.touchActivate());
    $('.range-slider').on("touchend", () => this.seekPos());
    this.playerService.initUrl("http://www.xamuel.com/blank-mp3-files/5min.mp3");
    this.subCounter();
  }

  subCounter() {
    this.counter = this.playerService.counter(this.song).subscribe(data => {
      this.pos = data;
      this.time.position = Math.round(this.pos);
      this.time.dur = this.song.duration - this.time.position;
      this.time.durMinutes = Math.floor(this.time.dur / 60);
      this.time.durSeconds = ('0' + Math.ceil(this.time.dur - this.time.durMinutes * 60)).slice(-2);
      this.time.posMinutes = Math.floor(this.time.position / 60);
      this.time.posSeconds = ('0' + Math.ceil(this.time.position - this.time.posMinutes * 60)).slice(-2);
      this.time.percent = this.time.position / this.song.duration * 100;
    })
  }

  dismiss() {
    this.viewCtrl.dismiss();
  }

  touchActivate() {
    this.counter.unsubscribe();
  }

  seekPos() {
    var ms = (this.song.duration * 1000) * (this.time.percent / 100);
    this.playerService.seek(ms);
    this.subCounter();
  }
}

玩家service.ts

import { Injectable } from '@angular/core';
import {MediaPlugin} from 'ionic-native';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';


@Injectable()
export class PlayerService {
  private media: any;
  public release: any;
  public song: any;
  private time: any;
  public playing: boolean;

  constructor() {
    this.time = {};
  }

  initUrl(release) {
    this.media = new MediaPlugin(release);
    this.media.play();
    console.log("ASDF");
    this.media.setVolume('0.0');
    //this.counter(null);
  }

  setRelease(release) {
    this.release = release;
    console.log('got it');
  }

  getStoredRelease() {
    //console.log(this.release);
    return this.release;
  }

  counter(song) {
    return Observable
      .interval(500)
      .flatMap(() => {
        return this.media.getCurrentPosition();
      });
  }

  seek(pos) {
    this.media.seekTo(pos);
  }

  pause() {
    this.playing = false;
    this.media.pause();
  }

  play() {
    this.playing = true;
    this.media.play();
  }
}

music.ts(调用模态的组件):

import {Component} from '@angular/core';
import {Modal, NavController, Loading} from 'ionic-angular';
import {ModalsContentPage} from '../player/player';
import {AlbumPage} from '../album/album';
import {ConnectService} from '../../providers/connect-service/connect-service';

@Component({
  templateUrl: 'build/pages/music/music.html',
  providers: [ConnectService]
})
export class MusicPage {
  public releases: any;
  private loading;

  constructor(private navController: NavController, private connectService: ConnectService) {
    this.loading = Loading.create();
    this.loadReleases();
  }

  openModal(release) {
    let modal = Modal.create(ModalsContentPage, release);
    this.navController.present(modal);
  }

  goToOtherPage() {
    //push another page onto the history stack
    //causing the nav controller to animate the new page in
    this.navController.push(AlbumPage);
  }

  loadReleases() {
    this.navController.present(this.loading);
    this.connectService.loadReleases()
      .then(data => {
        this.releases = data;
        this.loading.dismiss();
      });
  }
}

道歉,如果事情有点麻烦,我一直在评论试图让不同的技术发挥作用。

3 个答案:

答案 0 :(得分:1)

我不确定我是否理解您所遇到的问题,但您可以指定在modal被解雇时要执行的操作,例如:

openModal(release) {
  let modal = Modal.create(ModalsContentPage, release);

  // New code
  modal.onDismiss(data => {
      this.playerService.setRelease(data);
  });

  this.navController.present(modal);
}

这样,当modal被解雇时,您仍然可以使用您的服务保存数据。您可以找到有关Modal API here

的更多信息

======================================

修改

就像我在评论中提到的那样,试试这个:

而不是在service中将provider注册为Component

@Component({
  templateUrl: './build/pages/player/player.html',
  providers: [PlayerService, ...]
})

在您ionicBootstrap文件的app.ts中注册,如下所示:

ionicBootstrap(myApp, [PlayerService], {});

这样我们就可以确保在整个应用中使用该服务的相同实例(因此,它将是singleton)。

答案 1 :(得分:0)

this.playerService.setRelease(this params get ( 'release')..); 
console.log(this playerService getStoredRelease ()..);         // This works just after it is stored.

我的服务:

setRelease (release) {this. release = release; GetStoredRelease} () {return this. free; }

答案 2 :(得分:0)

  providers: [PlayerService, ConnectService]

该行创建了一个新的服务实例,这将使您的变量未初始化。

在引导程序或MusicPage提供程序行中实例化服务。然后像在构造函数中一样加载服务以访问实例化的服务。