Passing Data from Service to Component

13.3k views Asked by At

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?

1

There are 1 answers

3
Jarek On BEST ANSWER

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