[英]How to share function between sibling components in angular 4
我一直在閱讀我使用共享服務在2個組件(同級)之間共享數據,但是共享功能呢?
例如我有以下
服務
@Injectable()
export class SharedFunctionService {
//set these functions from the component in which it resides
//name scheme: componentname + function name + fn
comp1CancelFn: Function;
constructor() { }
}
comp1
export class comp1 {
constructor(private sharedFunctionService: SharedFunctionService,
private router:Router, private route: ActivatedRoute) {
this.sharedFunctionService.comp1CancelFn= this.onCancel;
}
onCancel():void{
this.router.navigate(['../'], {relativeTo:this.route});
}
}
然后我有comp2
export class comp2{
constructor(private sharedFunctionService: SharedFunctionService,
activatedRoute: ActivatedRoute, private router: Router) {
}
onCancel(){
this.sharedFunctionService.comp1CancelFn();
}
}
所以我將功能從comp1保存到服務中。 我的預期結果是,如果從comp2的某段html中調用了cancel函數,它將在服務中查找該函數並對其進行調用。 它做到了,但是我遇到的問題是,駐留在comp1中的所有變量都被認為是未定義的(在這種情況下,路由器但是即使我設置了一個簡單的名稱字符串並嘗試對其進行控制台記錄,它也是未定義的)。 有沒有辦法解決。 我從此來源和此來源提出了當前的解決方案。
當前使用angular 4.4.4版本,該服務位於app.module的我的根提供程序中
您可能還需要將共享函數使用的變量也移至共享服務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.