Home > database >  Angular's .navigateByUrl() navigates to the page but html is not rendered
Angular's .navigateByUrl() navigates to the page but html is not rendered

Time:05-30

I have a problem while navigating to home page after login. I have navbar <app-header></app-header> with two links, one to signup and another to login. After login i want to navigate to home page under http://localhost:4200 link. In login.component.ts i redirecting with navigateByUrl() and navigation works fine but my home page is not rendered, there is just blank white page. One thing that i realized is when i remove <app-header></app-header> from app.component.html my home page renders, but i loose my navigation bar. Where is the problem? How to render my homepage without getting rid of the navigation bar?

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { SignupComponent } from './auth/signup/signup.component';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { LoginComponent } from './auth/login/login.component';
import { NgxWebstorageModule } from 'ngx-webstorage';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
import { TokenInterceptor } from './token-interceptor';
import { HomeComponent } from './home/home.component';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';



@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    SignupComponent,
    LoginComponent,
    HomeComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HttpClientModule,
    NgxWebstorageModule.forRoot(),
    BrowserAnimationsModule,
    ToastrModule.forRoot(),
    FontAwesomeModule,
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './auth/login/login.component';
import { SignupComponent } from './auth/signup/signup.component';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {path:'', component: HomeComponent},
  {path:'signup', component: SignupComponent},
  {path:'login', component: LoginComponent},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.component.html

    <app-header></app-header>
    <router-outlet></router-outlet>

header.component.html

<header>
    <nav >
      <div >
        <a aria-label="Home"  routerLink="/">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" >
            <g>
              <circle fill="#FF4500" cx="10" cy="10" r="10"></circle>
              <path fill="#FFF"
                d="M16.67,10A1.46,1.46,0,0,0,14.2,9a7.12,7.12,0,0,0-3.85-1.23L11,4.65,13.14,5.1a1,1,0,1,0,.13-0.61L10.82,4a0.31,0.31,0,0,0-.37.24L9.71,7.71a7.14,7.14,0,0,0-3.9,1.23A1.46,1.46,0,1,0,4.2,11.33a2.87,2.87,0,0,0,0,.44c0,2.24,2.61,4.06,5.83,4.06s5.83-1.82,5.83-4.06a2.87,2.87,0,0,0,0-.44A1.46,1.46,0,0,0,16.67,10Zm-10,1a1,1,0,1,1,1,1A1,1,0,0,1,6.67,11Zm5.81,2.75a3.84,3.84,0,0,1-2.47.77,3.84,3.84,0,0,1-2.47-.77,0.27,0.27,0,0,1,.38-0.38A3.27,3.27,0,0,0,10,14a3.28,3.28,0,0,0,2.09-.61A0.27,0.27,0,1,1,12.48,13.79Zm-0.18-1.71a1,1,0,1,1,1-1A1,1,0,0,1,12.29,12.08Z">
              </path>
            </g>
          </svg>
          <span >
            Spring Reddit Clone
          </span>
        </a>
      </div>
      <div >
        <a routerLink="/signup" >Sign up</a>
        <a routerLink="/login" >Login</a>
      </div>
    </nav>
  </header>

login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from '../auth.service';
import { LoginRequestPayload } from './login-request.payload';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  isError = false;
  loginForm: FormGroup;
  loginRequestPayload: LoginRequestPayload;
  registerSuccessMessage:string;

  constructor(private authService: AuthService, private activatedRoute: ActivatedRoute, 
    private router: Router, private toastr: ToastrService) {
    
    this.loginForm = new FormGroup({
      username: new FormControl('', Validators.required),
      password: new FormControl('', Validators.required)
    }); 
    
    this.loginRequestPayload = {
      username: "",
      password: ""
    }
    this.registerSuccessMessage = "";
  }

  ngOnInit(): void {
    this.activatedRoute.queryParams.subscribe(params =>{
      if(params['registered'] !== undefined && params['registered'] === true){
        this.toastr.success("Signup Successful");
        this.registerSuccessMessage = "Please Check your inbox for activation email and activate your account before you login!"
      }
    })
  }
  
  login(){
    this.loginRequestPayload.username = this.loginForm.get('username')?.value;
    this.loginRequestPayload.password = this.loginForm.get('password')?.value;
    const self = this;
    this.authService.login(this.loginRequestPayload).subscribe({
      next(response){
        console.log(response);    
      },
      complete(){
        self.isError = false;
        self.toastr.success('Login Successful');
        self.router.navigateByUrl('');
      },
      error(){
        console.group("Error");
        self.isError = true;
      }
    })
  }
}

CodePudding user response:

You need to change this line

self.router.navigateByUrl('');

Should be like this if your intetion is to navigate to the root and render HomeComponent

self.router.navigateByUrl('/');

Remember that navigateByUrl() receives an absolute path string. The path for the root is '/' and not an empty string.

CodePudding user response:

Ok, i understood where is the problem. In my home page i have only one <h1>Home Page</h1> tag, so the page is actually rendered but the h1 tag stays under the navigation bar, thus i couldn't see it and decided that the page is not rendered.

  • Related