2017-09-05 31 views
1

这里有点棘手。我一直试图把我的头围绕着这个没有成功。好吧,这里有云......我得在设定了这样一个不同的离子成分的功能:将函数传递给Ionic 2或3中的另一个组件上的另一个函数

home.ts

playAudio() { 

    this.streamingMedia.playAudio('MY-URL'); 

    this.play = false; 

    } 

    stopAudio() { 
    this.streamingMedia.stopAudio(); 

    this.play = true; 
    } 

然后我建立这个布尔同一家庭内的.ts文件播放之间切换和暂停按钮

play: boolean = true; 

现在,在我的Home.html文件中我有它设置如下:

home.html的

<div *ngIf="play"> 
<img src="assets/img/play.png" class="play" (tap)="playAudio()" /> 
</div> 

<div *ngIf="!play"> 
<img src="assets/img/pause.png" class="play animated flip"  
(tap)="stopAudio()" /> 
</div> 

本质是什么这里发生的一切,当我点击播放按钮,开始播放,然后它显示的暂停按钮。同样,当我点击暂停按钮时,播放停止并显示播放按钮。

所以,这是我的问题,我试图调用不同的页面/组件中的函数。我希望它在我打开页面时自动播放流,我试图通过在app.component.ts文件中编写相同的playAudio()函数(如在home.ts文件中)来完成此操作,我需要设置函数:

app.component.ts

play: boolean = true; 

constructor() { 
this.playAudio(); } 

playAudio() {  
this.streamingMedia.playAudio('MY_URL'); 
this.play = false; 
} 

但页面打开时,流播放的,但我当时没有设置到位的播放按钮暂停按钮的选项。

我希望我有道理。

+0

您可以使用[NavParam](http://ionicframework.com/docs/api/navigation/NavParams/)将数据从您的'app.component.ts'发送到'home.ts',并将该数据用于显示或隐藏播放按钮。 – Duannx

回答

1

首先,一个建议: 在你的playAudio()功能在home.ts中,设置this.play = true,反之亦然stopAudio()。在你的html中,为!play而不是play做一个检查点,你有一个明智的逻辑,任何其他读取你的代码的人都可以理解。

为了您的困境,我建议使用角服务injectable

基本上,创建服务。装饰它作为注射剂。将它作为app.module.ts中的提供者引用,并将其注入到app.component.ts和home.ts的构造函数中。在该服务中写入并检索您的playAudio()stopAudio()

是这样的:

import {Injectable} from '@angular/core'; 
    import {StreamingMedia} from '@ionic-native/streaming-media'; 

    @Injectable() 
    export class PlayerService { 
    playing: boolean; 
    audioUrl: string = //whatever url; 

    //Inject your dependencies here 
    constructor(public streamingMedia: StreamingMedia){ 
     this.playing = false; 
    } 

    playAudio(){ 
    this.streamingMedia.playAudio(this.audioUrl); 
    this.playing = true; 
    } 

    stopAudio(){ 
    this.streamingMedia.stopAudio(); 
    this.playing = false; 
    } 

    } 

引用这是根据提供商部分在app.module.ts提供商:providers: [PlayerService]

在你的家。TS的构造,注射服务,你刚才提出

constructor(public playerService: PlayerService){} 

要使用playAudio()stopAudio()功能,只需键入 this.playerService.playAudio()等。使用服务的playing属性与html绑定。

我希望能用注射剂清除东西。

在你的app.component.ts中,像前面展示的那样在构造函数中注入服务。执行OnInit接口为

export class AppComponent implements OnInit {}然后创建ngOnInit(){}函数,您可以在其中调用服务的playAudio()函数以在初始化时开始播放。并使用服务的playing属性再次与UI结合。

+0

嗨安吉尔,感谢您的反馈!然而,作为一个新来的离子,“基本上,创造你的服务等......”不是什么基本的我:(你能提供一个例子,请我可以按照实现这个功能。对你的时间,这是表示赞赏。 –

+0

道歉!我的印象是,你有一阵子拨弄ionic3,并希望给我的方向一试,让我编辑我的答案。 –

+0

感谢您的上述。请详细说明'this.playerService.playAudio()'应该放在哪里,直接放在** home.ts **中,替换'playAudio()'作为敲击功能,或者让'(tap)=“playAudio ()“,就像在home.html中一样,然后在** home.ts **中将其设置为:'stopAudio(){this.playerService.playAudio();''无论哪种方式,我面临的挑战现在是我在过去的几个小时里尝试了所有这些选项,唯一不能工作的是play属性,button上面的方法不会改变。我已经尝试了几乎所有的东西 –

相关问题