使存储在提供者中的数据持久化

Make data stored in provider persistent

我正在使用 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();
      });
  }
}

抱歉,如果事情有点面条化,我一直在评论一些东西,试图让不同的技术发挥作用。

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; }

我不确定我是否理解您遇到的问题,但您可以指定 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 注册为 Component 中的 provider

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

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

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

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

  providers: [PlayerService, ConnectService]

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

在您的 bootstrap 或 MusicPage 提供商行中实例化该服务。然后像在构造函数中一样加载服务以访问实例化服务。