[英]Angular UI router resolve undefined in controller when return data in factory
[英]Angular 4 Router return undefined
我嘗試使用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: Cannot read property 'navigate' of undefined
at HomeComponent.nvgt (webpack-internal:///../../../../../src/app/home/home.component.ts:25)
at ZoneDelegate.invokeTask (webpack-internal:///../../../../zone.js/dist/zone.js:421)
at Object.onInvokeTask (webpack-internal:///../../../core/esm5/core.js:4940)
at ZoneDelegate.invokeTask (webpack-internal:///../../../../zone.js/dist/zone.js:420)
at Zone.runTask (webpack-internal:///../../../../zone.js/dist/zone.js:188)
at ZoneTask.invokeTask (webpack-internal:///../../../../zone.js/dist/zone.js:495)
at ZoneTask.invoke (webpack-internal:///../../../../zone.js/dist/zone.js:484)
at timer (webpack-internal:///../../../../zone.js/dist/zone.js:2065)
您已經失去this
的引用, this
是JS中很多人的典型問題。 更改此行:
window.setInterval(this.nvgt,1500,loc)
至
window.setInterval(() => this.nvgt(loc),1500)
您會看到,lambdas沒有上下文,這與典型的js函數不同(您在代碼中傳遞了方法的引用),而是堅持使用它們在其中被調用的上下文(類或另一個函數)。
btn2
點擊功能應該是navigator
<button #but2 id="but2" (click)="navigator('/inputphone')" mat-raised-button>Search specific phone</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.