Angular点击Bing Map图钉无法跳转:Router未定义问题求助
解决Bing Map图钉点击时Router未定义的问题
这个问题我之前踩过坑!核心原因就是回调函数的上下文绑定错误——当你给Bing Map的图钉绑定点击事件时,回调执行时的this指向的是图钉对象本身,而不是你的Angular组件实例,自然找不到你注入的router服务;但构造函数里的this是组件实例,所以调用router.navigate完全正常。
给你三种靠谱的解决方案,选哪种都能搞定:
方案1:用箭头函数定义回调(最推荐)
箭头函数会自动继承外层上下文的this,也就是你的组件实例,这样就能直接访问router了:
ngOnInit() { const location = new Microsoft.Maps.Location(47.6062, -122.3321); // 示例坐标 const pushpin = new Microsoft.Maps.Pushpin(location); // 给图钉绑定点击事件,用箭头函数 Microsoft.Maps.Events.addHandler(pushpin, 'click', () => { // 这里的this就是组件实例,router可以正常调用 this.router.navigate(['/device-detail']); }); // 记得把图钉添加到地图上 this.map.entities.push(pushpin); }
方案2:提前保存组件的this引用
在回调函数外先把组件的this存成变量(比如that),回调里用这个变量访问router:
ngOnInit() { const that = this; // 保存组件实例的this const location = new Microsoft.Maps.Location(47.6062, -122.3321); const pushpin = new Microsoft.Maps.Pushpin(location); Microsoft.Maps.Events.addHandler(pushpin, 'click', function() { // 用that访问组件的router that.router.navigate(['/device-detail']); // 注意:这里的this是图钉对象,如果需要图钉的元数据,可以用this.metadata }); this.map.entities.push(pushpin); }
方案3:用bind方法绑定上下文
直接给回调函数绑定组件的this,强制让回调里的this指向组件实例:
ngOnInit() { const location = new Microsoft.Maps.Location(47.6062, -122.3321); const pushpin = new Microsoft.Maps.Pushpin(location); Microsoft.Maps.Events.addHandler(pushpin, 'click', function() { this.router.navigate(['/device-detail']); }.bind(this)); // 绑定组件的this到回调函数 this.map.entities.push(pushpin); }
另外再确认下你的构造函数里已经正确注入了Router:
constructor(private router: Router, private activatedRoute: ActivatedRoute) { // 构造函数里的this是组件实例,所以这里调用this.router.navigate没问题 }
只要确保回调里的this指向组件实例,Router未定义的问题就解决啦!
内容的提问来源于stack exchange,提问作者Amit Khese
相关产品推荐
相关产品推荐

