WA E
WA E

Reputation: 33

Angular 2 Routing cannot match any routes

I am trying to re-route to a different page on log-in but for some reason my routes don't seem to be working. It keeps telling me that it "Cannot match any routes" in my router. I clearly have the route there, and I have tried all sorts of ways to make it match the path. Perhaps another set of eyes can see something I don't.

AppRouter.module:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { LoginComponent } from '../Components/login.component';
import { MenuComponent } from '../Components/menu.component';

const routes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'menu', component: MenuComponent }
];

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

login.component.module:

import { Component } from '@angular/core';
import { Router } from  '@angular/router';

@Component({
  templateUrl: '../Templates/login.component.html'
})
export class LoginComponent {
  title = 'app works!';
  username: string = 'user';
  password: string = 'password'

  constructor(private router: Router){

  }

  validate(): void{
    if(this.username === "user" &&
      this.password === "password"){
      console.log("Logged In!");
      this.router.navigate(['../main']);
    }
    else {
          console.log(this.username + ' ' + this.password);
    }
  }
}

It's imported into my module just fine, the menu.component is super basic, and there are no typos. If I add a "Route Link" inside an tag it will open, but no other way. Any ideas would be great, thanks.

Upvotes: 0

Views: 1265

Answers (2)

Artur Czopek
Artur Czopek

Reputation: 290

I think that you mispelled sth..

This is in your route config:

{ path: 'menu', component: MenuComponent }

And this is your component

this.router.navigate(['../main']);

Two different words: menu and main

Another problem in second case may be a two dots. You should use one because it's the same level (two dots its for going 'one level more')

Upvotes: 1

Teddy Sterne
Teddy Sterne

Reputation: 14201

Change this.router.navigate(['../main']); to this.router.navigate(['./menu']);. You do not want the router to go up a level because the two components are served from [host]/login and [host]/menu which are at the same level hierarchically.

Upvotes: 0

Related Questions