简体   繁体   中英

Angular 5 - Unable to navigate from one component to another component

I'm developing Angular application. In that I've two pages login and home. After login submit button it should navigate to home page. For this I tried multiple ways but it is not navigating to home page. Finally I used <router-outlet></router-outlet> in my login(app.component.html) file. So home page is displaying in login page. I want to navigate home page after login. Below is my current output and code

在此处输入图片说明

And when I'm refreshing http://localhost:4200/home it is showing errorlike below

在此处输入图片说明

app.component.html (login page)

<div align="center">
    <form (ngSubmit)="onLoginSubmit()" class="fullForm">

        <div class="imgcontainer"></div>
        <h2>PL Auth</h2>
        <div class="container">
            <form (ngSubmit)="generateOtpSubmit()" class="generateOtpForm">
                <label> <b>Username: </b>
                </label> <input type="text" placeholder="Enter Username" id="username"
                    [(ngModel)]=userName name="uname" required> <br> <br>
                <label> <b>Password : </b>
                </label> <input type="password" placeholder="Enter Password" id="password"
                    [(ngModel)]=password name="psw" required> <br> <br>
                <button type="submit" class="otpButton">Generate OTP</button>
            </form>
            <br> <br> <label> <b>Enter OTP : </b>
            </label> <input type="text" placeholder="Enter OTP" id="otp" [(ngModel)]=otp
                name="otp" required> <br> <br>
            <button type="submit" class="loginButton">Login</button>

        </div>
        <div>
            <p style="color: red;">{{ loginStatus }}</p>
        </div>
    </form>
    <router-outlet></router-outlet>
</div>

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { HomepageComponent } from './homepage/homepage.component';
import { Headers, Http, Response } from '@angular/http';
import {  RouterModule, Routes   } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Directive } from '@angular/core';
//import { Router } from '@angular/router'; 
import { Router } from "@angular/router";
import { Text } from '@angular/compiler';


export const appRoutes: Routes = [
   {path: 'home', component:HomepageComponent}
];

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

  otpsubmitted = false;
  loginSubmitted = false;
  userName = '';
  password = '';
  otp ='';
  userAuthCheck:Text;
  checkOtp:Text;
  authCheck ='';
  loginStatus='';

  ngOnInit() {
  }

  constructor(private http: Http,private httpClient: HttpClient,private route: Router ) { }

  private generateOtp(){
    this.http.post('http://localhost:8080/loginController/generateotp', {
      userMail: this.userName
    })
      .subscribe(
        res => {
          console.log(res);
        },
        err => {
          console.log("Error occured");
        }
      );
  }

  private logSubmit(){
    this.http.post('http://localhost:8080/loginController/authUser', {
      userMail: this.userName,
      password: this.password,
      otp: this.otp
    })
      .subscribe(
        res => {
          const printResp=res.json();
          console.log(res);
          //this.loginStatus=printResp.status;

          if (printResp.status === 'true'){
            this.loginStatus =  '';
            console.log('in the clickName');
            this.route.navigateByUrl('/home');
            //this.route.navigate(['home/']);
          } else if(printResp.status === 'false') {
                this.loginStatus =  printResp.Data.errorMessage;                          
          }
           },
        err => {
          console.log("Error occured"+err);
        }
      );
  }


  generateOtpSubmit() {
    this.otpsubmitted = true;
    this.generateOtp();
  }

  onLoginSubmit(){
    this.loginSubmitted = true;
    this.logSubmit();
  }
}

app-routing.module.ts

import {ApplicationComponent} from './application/application.component';
import {NavigationComponent} from './navigation/navigation.component';
import { HomepageComponent } from './homepage/homepage.component';
import {AppComponent} from './app.component';
import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import { CommonModule } from '@angular/common';


const routes: Routes = [
  {path: 'home', component: HomepageComponent},
  {path: 'application', component: ApplicationComponent},
  {path: 'navigation', component: NavigationComponent},
];

@NgModule({
  imports: [CommonModule,RouterModule.forRoot(routes)],
  exports: [RouterModule],
  declarations: []
})

export class AppRoutingModule {}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { Router } from '@angular/router';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
import { HomepageComponent } from './homepage/homepage.component';
import { ApplicationComponent } from './application/application.component';
import { NavigationComponent } from './navigation/navigation.component';
import { SearchuserComponent } from './searchuser/searchuser.component';

@NgModule({
  declarations: [
    AppComponent,
    HomepageComponent,
    ApplicationComponent,
    NavigationComponent,
    SearchuserComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    HttpModule,
    AppRoutingModule 
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

homepage.component.html

<p>
  homepage works!
</p>

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>CyberSecurityVw</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

homepage.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

只需使用

this.route.navigate(['/home']);

First :you will need to move your login form to a new component called (login)

second :your app component html should hold only this line

 <router-outlet></router-outlet> 

because app component will act like your landing page so you shouldn't add login form on it

Third : you need to modify your routing

import { HomepageComponent } from './homepage/homepage.component';
import { LoginComponent } from './login/login.component';
import { AppComponent } from './app.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CommonModule } from '@angular/common';


const routes: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    {
        path: 'home', component: HomepageComponent,
        children: [
            { path: '', redirectTo: '/example', pathMatch: 'full' },
            {
                path: 'example', component: ExampleComponent
            }
        ]
    },

    { path: 'login', component: LoginComponent },
];

@NgModule({
    imports: [CommonModule, RouterModule.forRoot(routes)],
    exports: [RouterModule],
    declarations: []
})

export class AppRoutingModule { }

-what will happen is when u type your website url without any routing it will navigate to home/example - so home component should contain your website design template so all children component will inject within home component and take the same template design

-login component is stand alone because u don't need it to take the same website design template

Fourth : in your home page html add this

<div>
   //your header 
     <header></header>
      <div class="content">
         <router-outlet></router-outlet>
     </div>
    // your footer
    <footer></footer>

  </div>
</div>

First add import in your main component

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

In the same file add below code for constructor and method

constructor(private route: Router) {}
public Dashbord()
{
  this.route.navigate(['/dashboard']);
}

In app-routing.module.ts file add dashboard

const routes: Routes =
[
  { path: '', pathMatch: 'full' ,component: TestComponent},
  { path: 'dashboard', component: DashboardComponent } 
];

This is your .html file code

<button mat-button (click)="Dashbord()">Dashboard</button><br>

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM