好吧,@John 提到的应该可行,但我建议你为你的问题提供一个通用的解决方案。通过添加指令组件,您不必在任何地方添加您的日志记录方法:
import {Directive, Renderer, ElementRef, HostListener} from "@angular/core";
@Directive({
selector: '[routerLink]'
})
export class FooClickTracker {
constructor(elementRef: ElementRef, renderer: Renderer) {
renderer.listen(elementRef.nativeElement, 'click', (event) => {
console.log('clicked', event, elementRef.nativeElement);
});
}
}
您可以验证侦听器将在路由发生之前执行:
constructor(elementRef:ElementRef, renderer:Renderer) {
renderer.listen(elementRef.nativeElement, 'click', (event) => {
console.log('clicked', event, elementRef.nativeElement);
this.sleep(5000)
});
}
// we can mock waiting for small period of time http://stackoverflow.com/questions/16873323/javascript-sleep-wait-before-continuing
private sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}