[英]Router undefined in Angular2
我想在成功進行用戶驗證后定義從登錄名到儀表板的重定向。 但是,當我在登錄組件中實現“ this.router.navigate(['/ dashboard'])”時,它給了我錯誤:“異常:未定義不是對象(評估“ this.router”)”
這是我實現該功能的方式:
export class ContactComponent implements OnInit {
contactForm: FormGroup;
errorMsg:string = '';
constructor(private formBuilder: FormBuilder, private _router: Router) {
this._router = _router;
}
ngOnInit() {
this.contactForm = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required],
});
DBEventProxy.instance(); // Init Eventbus
}
submitForm(): void {
DBEventProxy.instance().dbevent.login(this.contactForm['username'], this.contactForm['password'], this.loggedIn, this.failed);
}
loggedIn(): void {
this._router.navigate(['/dashboard']);
console.log("success");
DBEventProxy.instance().dbevent.register("disconnected", function (message) {
console.log("Client disconnected: " + JSON.stringify(message));
});
DBEventProxy.instance().dbevent.register("status", function (message) {
console.log("Client reconnected: " + JSON.stringify(message));
});
DBEventProxy.instance().dbevent.register("routeravailable", function (message) {
console.log("Router Available: " + JSON.stringify(message));
});
DBEventProxy.instance().dbevent.register("routerunavailable", function (message) {
console.log("Router Unavailable: " + JSON.stringify(message));
});
DBEventProxy.instance().dbevent.listen();
DBEventProxy.instance().dbevent.send({msgtype: "dashboardready"});
}
failed(message: string): void {
console.log("failed: " + message);
}
}
希望有人可以幫助我!
更新:使用登錄信息登錄時發生錯誤。 我從服務器獲得了ConnectReply,並且該連接存在。 但是重定向不起作用。 有多個錯誤。 我將嘗試在下面顯示這些內容:
路由配置:
export const rootRouterConfig: Routes = [
{ path: 'dashboard', component: DashboardComponent },
{ path: 'contact', component: ContactComponent },
{ path: '', redirectTo: '/contact', pathMatch: 'full'}
];
從構造函數中刪除此行:
this._router = _router;
在TypeScript中,當您將構造方法的參數聲明為public
或private
,將為您設置class屬性。
聽起來像this._router
就是所謂的上下文中, this
是不是你所期望的。 在submitForm
方法中,嘗試更改
this.loggedIn
至
()=>{this.loggedIn()}
嘗試這個
this._router.navigate(['dashboard']);
n條路線。
export const rootRouterConfig: Routes = [
{ path: '', component: ContactComponent},
{ path: 'dashboard', component: DashboardComponent },
{ path: 'contact', component: ContactComponent },
{ path: '**', redirectTo: '' }
];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.