[英]angular2 how to pass callback method from component into class (typescript file)
I have a class called data.ts. 我有一个名为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. 在订阅事件完成时,我想处理从服务器接收的数据并调用已调用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)
});
}
Should be more convenient return the Observable
and then subscribe from the caller. 应该更方便的是返回Observable
然后从调用者订阅。
myFunction() : Observable<any>{
return otherService.getData();
}
At the caller: 在来电者:
myFunction.subscribe((res: Response) => {
//use the response
});
To elaborate Fals' question based on your comment (as you haven't gotten an updated answer). 根据您的评论详细说明Fals的问题(因为您没有得到更新的答案)。
You can use .map
instead. 您可以改用.map
。 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
: 然后.subscribe
:
myFunction.subscribe(data => {
//do whatever you like
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.