Angular2路由器

时间:2017-02-28 09:40:49

标签: angular leaflet angular2-routing

所以我正在尝试Angular2(遵循在线教程)。 但是我在使用路由器时遇到了问题。

在我的component.ts中:

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

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

foo()从:

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

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

onMapClick-function是来自leaflet-lib的click-event。我可以点击地图和功能触发器。 但我明白了:

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

2 个答案:

答案 0 :(得分:3)

因为在onMapClick函数内,this未引用您的组件。它引用了click事件,并且该事件没有router属性。因此,this.router变为undefined

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

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

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

答案 1 :(得分:0)

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

constructor(private router:Router) {}