簡體   English   中英

Angular2中未定義的路由器

[英]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,並且該連接存在。 但是重定向不起作用。 有多個錯誤。 我將嘗試在下面顯示這些內容:

  1. 例外:未定義不是對象(評估“ this._router”)
  2. 原始堆棧:(此處有許多文檔和handleErrors)
  3. TypeError:未定義不是對象(評估“ this._router”)

路由配置:

export const rootRouterConfig: Routes = [
      { path: 'dashboard', component: DashboardComponent },
      { path: 'contact', component: ContactComponent },
      { path: '', redirectTo: '/contact', pathMatch: 'full'}
    ];

原始答案

從構造函數中刪除此行:

this._router = _router;

在TypeScript中,當您將構造方法的參數聲明為publicprivate ,將為您設置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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM