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?
In your case instead of @Output i recommend use observable Subject.
In your service, insted of:
Create new observable source and stream (Remember to import Subject from "rxjs/Subject"):
Insted of:
Send message by:
And then, in your component:
See: working example on Plunker
Read more about this solution: Angular.io - Communicate via a service