【问题标题】:Angular 5 - Unable to navigate from one component to another componentAngular 5 - 无法从一个组件导航到另一个组件
【发布时间】:2018-07-21 16:58:49
【问题描述】:

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

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

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

}

【问题讨论】:

  • 您在下面的其中一个 cmets 中提到了服务器请求的 404 错误。你投资了吗?这是针对哪个请求?

标签: javascript html angular ngroute


【解决方案1】:

随便用

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

【讨论】:

  • 加载资源失败:服务器响应状态为404(未找到)
  • 你能发布 home.component.ts 文件吗
  • 发布 home.comonent.ts
  • 文件夹中有模板吗
  • 是的,我有那个模板在问题中我错误地将其命名为 home.component.html。我会编辑
【解决方案2】:

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

第二个:你的应用组件 html 应该只包含这一行

 <router-outlet></router-outlet> 

因为应用程序组件的作用类似于您的登录页面,因此您不应在其上添加登录表单

第三:你需要修改你的路由

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

-当您在没有任何路由的情况下键入您的网站 url 时会发生什么,它将导航到 home/example - 所以 home 组件应该包含您的网站设计模板,因此所有子组件都将注入到 home 组件中并采用相同的模板设计

-登录组件是独立的,因为你不需要它来获取相同的网站设计模板

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

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

  </div>
</div>

【讨论】:

    【解决方案3】:

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

    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>
    

    祝你好运。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-27
      • 2018-05-31
      • 2018-05-31
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      • 2018-08-13
      • 1970-01-01
      相关资源
      最近更新 更多