简体   繁体   English

Angular2路由器

[英]Angular2 Router

So I'm trying Angular2 (following an onlinetutorial). 所以我正在尝试Angular2(遵循在线教程)。 But I'm having problems with navigating with Router. 但是我在使用路由器导航方面遇到了问题。

inside my component.ts: 在我的component.ts中:

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

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

The foo() is triggered from: foo()由以下内容触发:

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

(Just to test the navigation-function.) (只是为了测试导航功能。)

The onMapClick-function is click-event from leaflet-lib. onMapClick函数是来自leaflet-lib的click-event。 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);
  }

Because inside onMapClick function, this is not refering to your component. 因为在onMapClick函数内部, this不是指向您的组件。 It is refering to the click event, and the event doesn't have a router property. 它引用了click事件,并且该事件没有router属性。 Thus, this.router becomes undefined . 因此, this.router变得undefined

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

to

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

or 要么

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

您需要注入路由器才能使用它

constructor(private router:Router) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM