Search code examples
angulartypescriptangular8angular-routing

How to route the angular url to default component?


I am practicing by modifying the Tour of Heroes code.

I am in routing where if you pass nothing apart from localhost:4200 then it redirects to dashboard component.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroesComponent} from './heroes/heroes.component'

const routes: Routes = [{path: 'heroes', component: HeroesComponent},
                        {path: 'dashboard', component: DashboardComponent } ,
                        {path: '', redirectTo: '/dashboard', pathMatch:'full' },
                        ];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

but something weird is happening, if i remove this line

 {path: 'dashboard', component: DashboardComponent }

then it stops redirecting to the dashboard component. Why? It should not effect the routing to dashboard since it is just above the path:'' code and also I am not passing /dashboard in the url. Why it's effecting the default path code?


Solution

  • Affects it because your path is using the attribute "redirectTo" and that make reference to an existing path, in this case, "/dashboard" so, if that path doesn't exist (if you remove the path '/dashboard') the redirect will fail.

    enter image description here

    If you want to make a redirect without reference from another path, you could use Sander Wooming's suggestion