【问题标题】:Make data stored in provider persistent使存储在提供程序中的数据持久化
【发布时间】:2016-10-28 02:10:11
【问题描述】:

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

播放器服务.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();
      });
  }
}

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

【问题讨论】:

  • 发布更多代码,你的组件。
  • @dfsq 添加了我所有的代码。

标签: angular typescript ionic2 ionic3


【解决方案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 APIhere的信息。

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

编辑:

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

而不是将service 注册为providerComponent

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

从您的app.ts 文件中将其注册到ionicBootstrap,如下所示:

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

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

【讨论】:

  • 这仍然不起作用。我可以确认它会在模态消失时保存在我的 music.ts 中,但是当我再次打开模态时调用它时,它仍然是“未定义”。我试图将数据保留在我的服务中,因为模态经常被创建和销毁。
  • 我们可以尝试以下方法。我怀疑问题是因为每次加载组件时都会创建一个新的服务实例。为什么不在应用程序的bootstrap 中添加PlayerService,而不是在component 中添加呢?这样,服务将是一个单例,并且在整个应用程序中将使用相同的实例。
【解决方案2】:
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; }

【讨论】:

  • 这没有多大意义。 GetStoredRelease 是什么时候定义的,为什么到处都是空格?
【解决方案3】:
  providers: [PlayerService, ConnectService]

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 2018-04-03
    • 2014-09-24
    相关资源
    最近更新 更多