[英]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.