2017-02-28 212 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) {}