Passing a function to another function on a separate component in Ionic

Hi all,
A bit of a tricky one here. I’ve been trying to wrap my head around this one with no success. Ok, here it goes… I’ve got a function in a different ionic component set out like this:

home.ts

playAudio() { 

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

    this.play = true;

    }

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

    this.play = false;
    }

Then I set up this boolean within the same home.ts file to toggle between the play and pause buttons

play: boolean = false;

Now, in my home.html file I have it setup as follows:

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>

Essentially what is happening here is, when I click the play button, play starts and then it shows the pause button. And likewise, when I click the pause button, play stops and shows the play button.

So, here is my problem, I’m trying to call the function in a different page/component. I want it to automatically play the stream when I open the page, I tried doing that by writing the same playAudio() function (as in the home.ts file) in the app.component.ts file where I need to set the function:

app.component.ts

play: boolean = true;

constructor() {
this.playAudio(); }

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

but when the page opens, the stream plays but I then don’t have the option to set the pause button in place of the play button.

I hope I’m making sense.

Uhhhm, isn’t it as simple as just importing the home component in the app component, and calling this.home.playAudio()? :thinking: Or have I misunderstood?

Hi there… thanks, but I’m afraid it’s not as simple as your solution…

Did you try adding the play methods to a service instead?

As mich has said, it looks like you should have your audio streaming handled in a provider. You shouldn’t be calling methods of pages from other pages/components.

If you need your home page to display a play or pause button depending on if the audio is currently playing, you should have your audio provider expose an observable that the home page can subscribe to that will indicate whether the audio is currently playing or not.

1 Like

Realized that on my second reply, don’t know why I didn’t think of it while writing the first one :sweat_smile:

Hi Josh,
Thanks for your feedback… but as for someone who is learning “on the go” with Ionic, are you able to provide a possible example I can try and implement in my app. Unfortunately I don’t have the expertise of working with providers and observables, but if you can direct me down the right path that’ll be awesome.
Thank you all for your time. It is appreciated.