Bellal Mohamed
Bellal Mohamed

Reputation: 27

How to publish event from a component and receive it from another component in nativescript

How can I publish custom event from a component and receive it from another component in nativescript.

something like:

ComponentOne.ts
this.event.publish('someEvent', {name: 'a name'})

ComponentTwo.ts
this.event.subscribe('someEvent', (data) => {
    const name = data.name;
})

Upvotes: 1

Views: 1560

Answers (2)

Bellal Mohamed
Bellal Mohamed

Reputation: 27

Found a workaround. the basic idea is to register a custom event on the root frame of the app and listen on it from the other components

ComponentOne.ts
frameModule.topmost().notify({
    eventName: 'punched',
    object: frameModule.topmost(),
})
ComponentTwo.ts
frameModule.topmost().on('punched', () => {
   console.log('event received');
})

Upvotes: 0

Tony
Tony

Reputation: 20132

You can use subject for this case

import { Injectable } from "@angular/core";
import { Subject } from "rxjs";

@Injectable()
export class MessageService {
    private subject = new Subject<any>();

    constructor() {}

    sendMessage(message: any) {
        this.subject.next(message);
    }

    getData() {
        return this.subject.asObservable();
    }
}

I defined 2 method here. The first method using next() to send message to the next subcriber. So in your component you just need to simply subscribe like this to get the data

private subscription$: Subscription;

public ngOnInit(): void {
  this.subscription$ = this.messageervice
            .getData()
            .subscribe(data => { console.log(data); })
}

public ngOnDestroy(): void {
    this.subscription$.unsubscribe();
}

Upvotes: 3

Related Questions