Angular 5 - 无法从一个组件导航到另一个组件

时间:2018-02-11 11:24:17

标签: javascript html angular ngroute

我正在开发Angular应用程序。在那里我有两页登录和回家。登录提交按钮后,它应该导航到主页。为此我尝试了多种方法,但它没有导航到主页。最后,我在登录(app.component.html)文件中使用了<router-outlet></router-outlet>。所以主页显示在登录页面中。我想在登录后浏览主页。以下是我当前的输出和代码

enter image description here

当我刷新http://localhost:4200/home时,它会显示错误,如下所示

enter image description here

app.component.html(登录页面)

<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() {
  }

}

3 个答案:

答案 0 :(得分:1)

只需使用

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

答案 1 :(得分:1)

首先:您需要将登录表单移动到名为(login)的新组件

第二:你的app组件html应只包含这一行

 <router-outlet></router-outlet> 

因为app组件的行为与您的目标网页相同,因此您不应在其上添加登录表单

第三:您需要修改路由

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 { }

- 当你输入你的网站网址而没有任何路由它会导航到home / example时会发生什么 - 所以home组件应该包含你的网站设计模板所以所有的子组件都会注入home组件并采用相同的模板设计< / p>

-login组件是独立的,因为你不需要它来采用相同的网站设计模板

第四:在你的主页html添加这个

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

  </div>
</div>

答案 2 :(得分:0)

首先在您的主要组件中添加导入

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

在同一文件中,为构造函数和方法添加以下代码

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

app-routing.module.ts文件中添加dashboard

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

这是您的.html文件代码

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

祝你好运。