1

I have a class called data.ts. In that i have a method which is called from various components. This method subscribes the data from another service. On the completion of subscribe event i want to process the data received from server and call the callback method of component who has invoked myFunction. Is that possible to do? something like below:

myFunction(callback: function) {
    otherService.getData().subscribe((res: Response) => {
        //do some processing of response
        caller.callback(processed_response)
    });
}
0

2 Answers 2

2

Should be more convenient return the Observable and then subscribe from the caller.

myFunction() : Observable<any>{
    return otherService.getData();
}

At the caller:

myFunction.subscribe((res: Response) => {
        //use the response
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply. it would work but if i want to do some processing of data before returning then what should i do?
1

To elaborate Fals' question based on your comment (as you haven't gotten an updated answer).

You can use .map instead. You have probably mapped the response once earlier, but you can map several times.

 myFunction() : Observable<any>{
    return otherService.getData()
      .map(res => {
         return ... // your processing
      })
}

and then .subscribe:

myFunction.subscribe(data => {
   //do whatever you like
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.