【发布时间】:2018-04-05 11:22:54
【问题描述】:
我一直在阅读我使用共享服务在 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 中调用取消函数,它将在服务中查找该函数并调用它。它会这样做,但我遇到的问题是所有驻留在 comp1 中的变量都被认为是未定义的(在这种情况下是路由器,但即使我设置了一个简单的名称字符串并尝试通过控制台记录它,它也是未定义的)。有没有办法解决。我从这个source 和这个source 提出了我目前的解决方案。
当前使用 Angular 4.4.4 版本,该服务在我的 app.module 中的根提供程序中
【问题讨论】:
标签: angular typescript service