angular 7 redirecting to another page

15,545

Solution 1

In Routes you have only one route - to dashboard - make second route to login

Solution 2

You should have another route to the login page. Without having that, you can't make any call to the login page.

In your part of code, Try these chunks of code

app.component.ts

authenticateLogin(user){
    let authUser = JSON.parse(localStorage.getItem('auth'))
    console.log(user);
    if(user.mail === authUser[0] && user.password === authUser[1]){
      this.showWhen = true;
      console.log("Logged in Successfully");
      this._router.navigate(['dashboard']);
    } else {
      this._router.navigate(['login']);
    }
  }

and you should have another router path in

app-routing.module.ts

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent} ,
  { path: 'login', component: LoginComponent(write your login component name)} 
];
Share:
15,545
Ben
Author by

Ben

I am a full stack developer.

Updated on July 10, 2022

Comments

  • Ben
    Ben almost 2 years

    I have a login page and a dashboard component.My problem is when i login from the page the dashboard displays below the login page, it is not redirecting as a new page.How to achieve this in angular 7? Any help would be helpful'. Thanks!!

    app.component.ts

    import { Component } from '@angular/core';
    import { Router } from '@angular/router';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    
    export class AppComponent {
      title = 'Shopping-cart';
      user = []
      users = []
      public Candidate = []
      public showWhen:boolean = false;
    
      constructor(private _router: Router){}
    
      authenticateLogin(user){
        let authUser = JSON.parse(localStorage.getItem('auth'))
        console.log(user);
        if(user.mail === authUser[0] && user.password === authUser[1]){
          this.showWhen = true;
          console.log("Logged in Successfully");
          this._router.navigate(['dashboard']);
        } else {
          console.error("Invalid email and password");
        }
      }
    
    }
    

    This is my routing-module

    app-routing.module.ts

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { DashboardComponent } from './dashboard/dashboard.component';
    
    const routes: Routes = [
      { path: 'dashboard', component: DashboardComponent} 
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes, { enableTracing: true })],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    
  • Ben
    Ben over 5 years
    yes, i have done like that only and the problem was I din't add it to the route