路由器不导航

Router not navigating

我正在加载登录组件,但是当我按下登录按钮时,url 变为 Dashboard 但没有其他任何事情发生,我在控制台或任何地方都没有看到任何错误,因此我无法诊断问题。我确定这很简单但没有错误,我不确定该怎么做?

导航:

public onLogin(value: any) {
  this.router.navigateByUrl('/dashboard')


// this.loginService.onLogin(value)
//   .subscribe(
//     value => {
//       console.log('[POST] login Registrant successfully', value);
//     }, error => {
//       console.log('FAIL to login Registrant!');
//     },
//     () => {
//       console.log('POST Registrants - now completed.');
//     });
  this.submitted = true;
}

路由模块:

import { Routes, RouterModule } from '@angular/router';
import { ModuleWithProviders } from '@angular/core';
import {LoginComponent} from "./login/login.component";
import {DashboardComponent} from "./dashboard/dashboard.component";


export const appRouter: Routes = [
  {
    path: '**',
    component: LoginComponent
  },
  {
    path: 'dashboard',
    component: DashboardComponent
  }
];

export const appRoutes: ModuleWithProviders = RouterModule.forRoot(appRouter);

首先不要使用通配符路由作为您的登录路由..

基本上你的通配符路由是如果有人到达一个不存在的路由显示某个组件,如果你把它放在你的路由堆栈的顶部..无论如何路由总是路由到通配符

您的路由组件应如下所示..

export const appRouter: Routes = [
  {
    path: '',
    component: LoginComponent
    pathMatch: full
  },
  {
    path: 'dashboard',
    component: DashboardComponent
  },
  {
    path: '**',
    component: PageNotFoundComponent
  },

];

通配符路由 ** 用于页面未找到的组件,并始终确保它在末尾

然后在您的登录组件中改用它

this.router.navigate(['dashboard']);

你的app.module说。

export const appRouter: Routes = [
  {
    path: '**',
    component: LoginComponent
  },
  {
    path: 'dashboard',
    component: DashboardComponent
  }
];

path: '**' 将匹配每个链接。因此,无论路由如何,LoginComponent 都将为 return。尝试更改顺序。喜欢

export const appRouter: Routes = [
      {
        path: 'dashboard',
        component: DashboardComponent
      },
      {
        path: '**',
        component: LoginComponent
      }
    ];

始终将 path: '**' 放在末尾。这意味着如果所有路径都失败,匹配这个。