alexfyren
alexfyren

Reputation: 203

Angular2 Router

So I'm trying Angular2 (following an onlinetutorial). But I'm having problems with navigating with Router.

inside my component.ts:

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

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

The foo() is triggered from:

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

(Just to test the navigation-function.)

The onMapClick-function is click-event from leaflet-lib. I can click on the map and the function triggers. But I get:

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..

These functions are right after eachother... Why does one work, but the other not?

This is where I trigger the event:

    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);
  }

Upvotes: 1

Views: 157

Answers (2)

eko
eko

Reputation: 40647

Because inside onMapClick function, this is not refering to your component. It is refering to the click event, and the event doesn't have a router property. Thus, this.router becomes undefined.

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

to

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

or

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

Upvotes: 3

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657308

You need to inject the router in order to be able to use it

constructor(private router:Router) {}

Upvotes: 0

Related Questions