我尝试使用 Router.navigate({})
创建一个函数
导入路由器:import { Router } from '@angular/router';
具有函数和构造函数的类:
export class HomeComponent implements OnInit {
constructor(private router:Router,private renderer: Renderer2,public but2: ElementRef, public but1: ElementRef) {
}
ngOnInit() {
}
nvgt(lc){
this.router.navigate([ lc ]);
}
navigator(loc) {
this.renderer.setStyle(this.but1.nativeElement.querySelector('#but1'),'animation','fadeoutdown 1s both');
this.renderer.setStyle(this.but2.nativeElement.querySelector('#but2'),'animation','fadeoutup 1s both');
window.setInterval(this.nvgt,1500,loc)
}
}
组件HTML(2个按钮):
<button #but1 id="but1" (click)="navigator('/questions')" mat-raised-button>Search for my next phone</button>
<hr data-content="OR">
<button #but2 id="but2" (click)="navigate('/inputphone')" mat-raised-button>Search specific phone</button>
当我单击控制台中发现的下一个错误时:
ERROR TypeError:无法在HomeComponent.nvgt中读取未定义的属性'navigate'(webpack-internal:///../../../../../src/app/home/home.component.ts :25)at.DevokeTask(webpack-internal:///../../../../ zone.js /../../../core/esm5/core.js:4940)在ZoneDelegate.invokeTask(webpack-internal:///../../../../zone.js/dist/ zone.run:420)在ZoneTask.invokeTask(webpack-internal)的Zone.runTask(webpack-internal:///../../../../zone.js/dist/zone.js:188) :///../../../../zone.js/dist/zone.js:495)在ZoneTask.invoke(webpack-internal:///../../../ . ./zone.js/dist/zone.js:484)在计时器(webpack-internal:///../../../../zone.js/dist/zone.js:2065)
谢谢你的帮助!
2 回答
你已经失去了对
this
的引用,这是JS中许多人的典型问题 . 改变这一行:至
你看,lambdas没有上下文,不像典型的js函数(你在代码中传递一个方法的引用),而是坚持它们被调用的上下文(一个类或另一个函数) .
btn2
点击功能应为navigator