5

Before someone mark this as duplicate Below are the links that I tried and failed

Angular 2 - passing data from service to component

How to subscribe to an event on a service in Angular2?

Scenario I want to sent data from my ng2 service to component and the data is being loaded from an API using ng2 HTTP

Below is the dummy code

MyService

@Output() event_callback: EventEmitter<any> = new EventEmitter();

getUserDetails(id)
{
    var user_data;
    this.loadRemoteUrl('getUserdata?user_id=' + id).subscribe(
        data => { user_data = data},
        err => console.error(err),
        () => {
            console.log('Inside My Service');
            this.user_data = user_data;
            this.event_callback.emit(this.user_data);
        }
    );
}

MyComponent

constructor(private http:Http, private myService: MyService) 
{
    var userDetails;
    myService.event_callback.subscribe(
        data => this.callbackFunction()
    );
}

callbackFunction()
{
    console.log("Inside MyComponent")
}

Console Log

Inside My Service

The HTTP request is returning data properly which I tried dumping before emit and it worked but problem is I am unable to access data in my component, I tried passing data,now I am just some logging messages to identify flow but still unable to see the log message from my component file.

What did I miss?

Community
  • 1
  • 1
Akshay Khale
  • 8,151
  • 8
  • 50
  • 58

1 Answers1

8

In your case instead of @Output i recommend use observable Subject.

In your service, insted of:

@Output() event_callback: EventEmitter<any> = new EventEmitter();

Create new observable source and stream (Remember to import Subject from "rxjs/Subject"):

private eventCallback = new Subject<string>(); // Source
eventCallback$ = this.eventCallback.asObservable(); // Stream

Insted of:

this.event_callback.emit(this.user_data);

Send message by:

this.eventCallback.next(this.user_data);

And then, in your component:

myService.eventCallback$.subscribe(data => {
    this.callbackFunction();
});

See: working example on Plunker

Read more about this solution: Angular.io - Communicate via a service

Jarek
  • 947
  • 1
  • 7
  • 19
  • I already tried that didn't work, But as per my knowledge they both work in the same way and `emit` is in latest Angular, where as `next` is in older version, thanks for the efforts... – Akshay Khale Dec 21 '16 at 14:08
  • 2
    @AkshayKhale I have added working example on plunker, check it out: https://plnkr.co/edit/Hhc6lTSwGQWP3zq2Ttlu?p=preview – Jarek Dec 21 '16 at 14:19
  • @jarek Thank you for the plunkr helped me out a ton! One little issue with it. private eventCallback: Subject = new Subject(); Should be private eventCallback: Subject = new Subject(); *removed the array syntax* if you want to pass just a string. – laymanje Jun 16 '17 at 19:45
  • Yes @Jarek thanks for that Plunkr! – Jonathan Jun 13 '23 at 20:27