最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 8 this.router.navigate() changes URL but not rendering to next page - Stack Overflow

programmeradmin3浏览0评论

I'm quite new with Angular and I am setting up the front end of a project in Angular 8 that will eventually use REST API's to display data. Currently I have created 2 custom components.

  1. LoginComponent
  2. HomeComponent

My goal is only to be redirected to HomeComponent html from LoginComponent html when I click the login button.

Both LoginComponent and HomeComponent are in the same directory level.

Below are the contents of the files.

app.module.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    
    import { AppComponent } from './appponent';
    import { PageNotFoundComponent } from './page-not-found/page-not-foundponent';
    import { AppRoutingModule } from './app-routing.module';
    import { ErrorPageComponent } from './error-page/error-pageponent';
    import { HeaderComponent } from './header/headerponent';
    import { LoginComponent } from './login/loginponent';
    import { HomeComponent } from './home/homeponent';
    
    @NgModule({
      declarations: [
        AppComponent,
        PageNotFoundComponent,
        ErrorPageComponent,
        HeaderComponent,
        LoginComponent,
        HomeComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        AppRoutingModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

app-routing.module.ts

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { PageNotFoundComponent } from './page-not-found/page-not-foundponent';
    import { ErrorPageComponent } from './error-page/error-pageponent';
    import {LoginComponent} from './login/loginponent';
    import {HomeComponent} from './home/homeponent';
    
    const appRoutes: Routes = [
      { path: '', component : LoginComponent},
      { path: 'home', component : HomeComponent },
      { path: 'not-found', component: PageNotFoundComponent },
      { path: '**', redirectTo: '/not-found' }
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(appRoutes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule {
    
    }

appponent.html

    <div class="web-container">
    
      <div>
      <app-header>
        <meta name="viewport" content="width=device-width, initial-scale=1">
      </app-header>
      </div>
    
      <app-login></app-login>
      <router-outlet></router-outlet>
    
    </div>

loginponent.ts

    import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    
    @Component({
      selector: 'app-login',
      templateUrl: './loginponent.html',
      styleUrls: ['./loginponent.css']
    })
    export class LoginComponent implements OnInit {
    
      constructor(private router: Router) { }
    
      ngOnInit() {
      }
    
      public onLoginClick(){
        console.log("Login Clicked");
        this.router.navigate(['./home']);
      }
    
    }

loginponent.html

    <div class="content">
      <h3>Login</h3>
      <hr />
      <form>
        <button class="btn btn-primary mybtn-login" (click)="onLoginClick()" >Login</button>
      </form>     
    </div>

homeponent.html

    <h1  style="color:yellow;">home works!</h1>

homeponent.ts

    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-home',
      templateUrl: './homeponent.html',
      styleUrls: ['./homeponent.css']
    })
    export class HomeComponent implements OnInit {
      constructor() { }
    
      ngOnInit() { }
    }

Problem

When I click on the Login button, I can see in the browser that it changes the url from http://localhost:4200/ to http://localhost:4200/home. However, it doesn't display any of the contents of homeponent.html

It just stays on the login page view and nothing changes on the page.

I'm really confused why it would change the URL but not render the page. I tried adding <router-outlet> to loginponent.html which displays the home inside the login page. But ofcourse we don't want to stay/keep showing the login page.

Thanks in advance.

I'm quite new with Angular and I am setting up the front end of a project in Angular 8 that will eventually use REST API's to display data. Currently I have created 2 custom components.

  1. LoginComponent
  2. HomeComponent

My goal is only to be redirected to HomeComponent html from LoginComponent html when I click the login button.

Both LoginComponent and HomeComponent are in the same directory level.

Below are the contents of the files.

app.module.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    
    import { AppComponent } from './app.component';
    import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
    import { AppRoutingModule } from './app-routing.module';
    import { ErrorPageComponent } from './error-page/error-page.component';
    import { HeaderComponent } from './header/header.component';
    import { LoginComponent } from './login/login.component';
    import { HomeComponent } from './home/home.component';
    
    @NgModule({
      declarations: [
        AppComponent,
        PageNotFoundComponent,
        ErrorPageComponent,
        HeaderComponent,
        LoginComponent,
        HomeComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        AppRoutingModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

app-routing.module.ts

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
    import { ErrorPageComponent } from './error-page/error-page.component';
    import {LoginComponent} from './login/login.component';
    import {HomeComponent} from './home/home.component';
    
    const appRoutes: Routes = [
      { path: '', component : LoginComponent},
      { path: 'home', component : HomeComponent },
      { path: 'not-found', component: PageNotFoundComponent },
      { path: '**', redirectTo: '/not-found' }
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(appRoutes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule {
    
    }

app.component.html

    <div class="web-container">
    
      <div>
      <app-header>
        <meta name="viewport" content="width=device-width, initial-scale=1">
      </app-header>
      </div>
    
      <app-login></app-login>
      <router-outlet></router-outlet>
    
    </div>

login.component.ts

    import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    
    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css']
    })
    export class LoginComponent implements OnInit {
    
      constructor(private router: Router) { }
    
      ngOnInit() {
      }
    
      public onLoginClick(){
        console.log("Login Clicked");
        this.router.navigate(['./home']);
      }
    
    }

login.component.html

    <div class="content">
      <h3>Login</h3>
      <hr />
      <form>
        <button class="btn btn-primary mybtn-login" (click)="onLoginClick()" >Login</button>
      </form>     
    </div>

home.component.html

    <h1  style="color:yellow;">home works!</h1>

home.component.ts

    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.css']
    })
    export class HomeComponent implements OnInit {
      constructor() { }
    
      ngOnInit() { }
    }

Problem

When I click on the Login button, I can see in the browser that it changes the url from http://localhost:4200/ to http://localhost:4200/home. However, it doesn't display any of the contents of home.component.html

It just stays on the login page view and nothing changes on the page.

I'm really confused why it would change the URL but not render the page. I tried adding <router-outlet> to login.component.html which displays the home inside the login page. But ofcourse we don't want to stay/keep showing the login page.

Thanks in advance.

Share Improve this question edited Aug 30, 2021 at 9:25 NeNaD 20.3k9 gold badges61 silver badges111 bronze badges asked Aug 30, 2021 at 8:28 heisenbergheisenberg 1,9544 gold badges39 silver badges75 bronze badges 6
  • You don't need dot in router navigation this.router.navigate(['/home']); – Beller Commented Aug 30, 2021 at 8:31
  • 1 try change this line this.router.navigate(['./home']); with this one this.router.navigate(['/home']); – Raycas Commented Aug 30, 2021 at 8:31
  • @Raycas I tried removing the . dot but when I click on the login button, it just won't go to the home page. This problem is really strange. – heisenberg Commented Aug 30, 2021 at 8:56
  • @Beller I tried without the dot but didn't work. :( – heisenberg Commented Aug 30, 2021 at 8:56
  • @jordan Can you see something error in the console? – Beller Commented Aug 30, 2021 at 9:06
 |  Show 1 more comment

3 Answers 3

Reset to default 9

You added both <app-login></app-login> and <router-outlet></router-outlet> in your app.component.html. That means that Login component will always be displayed on the screen, and the content below it will change. Your Home component probably got rendered, but you didn't see it because of the Login page that stayed on the screen. Just remove the <app-login></app-login> since it will be automatically rendered with <router-outlet></router-outlet>, so you don't need to specify it explicitly.

<div class="web-container">

  <div>
  <app-header>
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </app-header>
  </div>

  <router-outlet></router-outlet>

</div>

Looks like it's not hitting the route and falling back to the empty one

  { path: '', component : LoginComponent},  <--- falling back on this
  { path: 'home', component : HomeComponent },
  { path: 'not-found', component: PageNotFoundComponent },
  { path: '**', redirectTo: '/not-found' }

In that way, you will see it loading the same route you are on. Your router is one level depth so this.router.navigate(['./home']); is searching in an undefined level, causing the fallback

this.route.navigate(['/home']) should work

Remember routing is not necessarily navigating to a component directory rather to the path/route that you defined on the app-routing.module.ts file.

The app-routing.module.ts file is the one that deals with the component that needs to be loaded based on how you defined the path on the Routes in the routing module.

Hence you need to remove the dot and put it like this:

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

The router will figure out which component needs to be loaded as defined in the paths on app-routing.module.ts file.

Even if the component wasn't in the same directory as the LoginComponent, so long as you had defined the path 'home' path in the router to link to the HomeComponent, the router would know which file to load.

发布评论

评论列表(0)

  1. 暂无评论