2017-02-28 151 views
1

所以我想Angular2(在线教程)。 但我在使用路由器导航时遇到问题。Angular2路由器

我component.ts内:

<a (click)="foo()">test</a> 

(只是为了测试导航功能)

的onMapClick功能:

foo() { 
    this.router.navigate(['/myroute']); 
    } 

    onMapClick(e) { 
    this.router.navigate(['/myroute']); 
    } 

,把foo()从触发是leaflet-lib中的点击事件。我可以点击地图并触发功能。 但我得到:

EXCEPTION: Cannot read property 'navigate' of undefined 
ErrorHandler.handleError @ error_handler.js:54 
next @ application_ref.js:348 
schedulerFn @ async.js:93 
SafeSubscriber.__tryOrUnsub @ Subscriber.js:234 
SafeSubscriber.next @ Subscriber.js:183 
Subscriber._next @ Subscriber.js:125 
Subscriber.next @ Subscriber.js:89 
Subject.next @ Subject.js:55 
EventEmitter.emit @ async.js:79 
NgZone.triggerError @ ng_zone.js:333 
onHandleError @ ng_zone.js:294 
ZoneDelegate.handleError @ zone.js:334 
Zone.runTask @ zone.js:169 
ZoneTask.invoke @ zone.js:416 
error_handler.js:59 ORIGINAL STACKTRACE: 
ErrorHandler.handleError @ error_handler.js:59 
next @ application_ref.js:348 
schedulerFn @ async.js:93 
SafeSubscriber.__tryOrUnsub @ Subscriber.js:234 
SafeSubscriber.next @ Subscriber.js:183 
Subscriber._next @ Subscriber.js:125 
Subscriber.next @ Subscriber.js:89 
Subject.next @ Subject.js:55 
EventEmitter.emit @ async.js:79 
NgZone.triggerError @ ng_zone.js:333 
onHandleError @ ng_zone.js:294 
ZoneDelegate.handleError @ zone.js:334 
Zone.runTask @ zone.js:169 
ZoneTask.invoke @ zone.js:416 
ETC.. 

这些功能后海誓山盟正确的...为什么一个工作,但其他呢?

这是我触发事件:

constructor(
    private router: Router 
) { } 

    ngOnInit() { 
    this.drawMap(); 
    } 

    drawMap() { 
    var map = L.map('map').setView([0, 0], 3); 

    L.tileLayer('maptiles/{z}/{x}/{y}.png', { 
     minZoom: 3, 
     maxZoom: 4, 
     continuousWorld: false, 
     noWrap: true, 
     crs: L.CRS.Simple, 
    }).addTo(map); 

    map.on('click', this.onMapClick); 
    } 
+0

请张贴的链接教程。 –

+0

https://github.com/bradtraversy/meanauthapp – alexfyren

回答

3

因为里面onMapClick功能,this不是指的你的组件。它指的是点击事件,并且该事件没有router属性。因此,this.router变为undefined

变化:map.on('click', this.onMapClick);

map.on('click', this.onMapClick.bind(this)); 

map.on('click',()=>{this.onMapClick();}); 
+0

该事件只是触发一个功能。我可以从参数中删除事件: onMapClick(){ this.router.navigate(['/ myroute']); } 仍然没有改变,我在想错吗? :) – alexfyren

+0

@alexfyren你可以分享你触发这个功能的代码吗? – echonax

+0

我会加上问题;) – alexfyren

0

你需要为了注入路由器能够使用它

constructor(private router:Router) {}