[英]How to call Typescript method from Javascript callback method - Angular2
[英]angular2 how to pass callback method from component into class (typescript file)
我有一個名為data.ts的類。 因為我有一個從各種組件調用的方法。 此方法訂閱來自其他服務的數據。 在訂閱事件完成時,我想處理從服務器接收的數據並調用已調用myFunction的組件的回調方法。 這可能嗎? 如下所示:
myFunction(callback: function) {
otherService.getData().subscribe((res: Response) => {
//do some processing of response
caller.callback(processed_response)
});
}
應該更方便的是返回Observable
然后從調用者訂閱。
myFunction() : Observable<any>{
return otherService.getData();
}
在來電者:
myFunction.subscribe((res: Response) => {
//use the response
});
根據您的評論詳細說明Fals的問題(因為您沒有得到更新的答案)。
您可以改用.map
。 您可能先前已映射過響應,但您可以多次映射。
myFunction() : Observable<any>{
return otherService.getData()
.map(res => {
return ... // your processing
})
}
然后.subscribe
:
myFunction.subscribe(data => {
//do whatever you like
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.