When using Angular's .navigateByUrl() method, it successfully navigates to the desired page, however the html content is not

Whenever I try to navigate to the home page after logging in, I encounter an issue. I have a navbar

<app-header></app-header>
with two links - one for signing up and another for logging in. After successfully logging in, my goal is to navigate to the home page under the link http://localhost:4200. In the login.component.ts, I use navigateByUrl() for redirection and the navigation itself works fine. However, the problem arises when my home page does not render properly, showing only a blank white page. Upon investigation, I found that removing
<app-header></app-header>
from app.component.html results in the home page rendering correctly, though at the cost of losing the navigation bar. How can I resolve this issue and render my homepage without sacrificing 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 class="navbar fixed-top navbar-expand-lg navbar-light bg-light">
      <div class="flex-grow-1">
        <a aria-label="Home" class="logo" routerLink="/">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" class="reddit-icon-svg">
            <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 class="reddit-text">
            Spring Reddit Clone
          </span>
        </a>
      </div>
      <div class="flex-grow-1 float-right">
        <a routerLink="/signup" class="float-right sign-up mr-2">Sign up</a>
        <a routerLink="/login" class="float-right login mr-2">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(){
        group("Error");
        self.isError = true;
      }
    })
  }
}

Answer №1

I encountered a similar issue. This is the code I used:

this.router.navigate(["./do-list/"+this.filter]);

However, instead of reloading the page, it simply changed the URL. To address this, I utilized JavaScript to manually reload the page.

window.location.reload();

Answer №2

This line needs to be revised

self.router.navigateByUrl('');

If you intend to navigate to the root and display the HomeComponent, it should look like this

self.router.navigateByUrl('/');

Keep in mind that navigateByUrl() requires an absolute path string. The path for the root is '/', not an empty string.

Answer №3

Aha! I have pinpointed the issue. On my homepage, there is only a single <h1>Home Page</h1> tag. As a result, the page is technically rendered, but the h1 tag gets hidden beneath the navigation bar, leading me to mistakenly believe that the page was not rendering properly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Protractor Jasmine experiencing issues with describe block within the it block

I am currently exploring Jasmine and attempting to incorporate shared steps in my test cases. I want to reuse certain steps between two scenarios, but when I try to execute a common describe block inside an it block, it does not run as expected. Here is a ...

Guide on transitioning Angular 2 RC 1 (or an earlier version) Forms to the new Forms in Angular 2 RC 2 / RC 4

I am currently in the process of upgrading my Angular 2 RC 1 app to Angular 2 RC 4, and part of this update involves migrating my existing forms to Angular 2 RC 4 New Forms. Could someone provide guidance on how to successfully update my existing forms to ...

Invoking a method in a derived class upon completion of asynchronous logic within the base class

Currently, I am in the process of building an Angular application. One aspect of my project involves a class that extends a base class. While this approach may not be ideal, I am curious to know what would be the best practice for BaseClass to trigger me ...

Angular 5 does not recognize the function submitEl.triggerEventHandler, resulting in an error

Greetings! I am currently working on writing unit test cases in Angular5 Jasmine related to submitting a form. Below is the structure of my form: <form *ngIf="formResetToggle" class="form-horizontal" name="scopesEditorForm" #f="ngForm" novalidate (ngSu ...

Trouble viewing Three.js content in Index.html

My current project involves building a website using three.js with typescript. However, I am facing an issue where only the header from my index.html file is displayed when I try to load the website onto a local server. The main problem arises when I atte ...

Can you guide me on utilizing the drag and drop functionality in Angular 8 CDK to merge two cards together?

My current challenge involves attempting to drag one card over another card in order to effectively "merge" or "combine" them, similar to the action of dragging an image onto a folder on a desktop. Despite utilizing HTML5 native drag and drop functionalit ...

Azure pipeline failing to run Visual Studio 2017 task because of outdated Typescript SDK version

The Visual Studio 2017 build encounters an error during the build process src\Service\node_modules\utility-types\dist\aliases-and-guards.d.ts(10,51): Error TS2304: Build:Cannot find name 'bigint This issue is specific to the ...

Angular JS and TypeScript - Issue: ng:areq Invalid Argument "Argument 'XXXXXX' is not a function, received undefined"

Encountering a specific error mentioned in the title. I organized models and controllers into distinct files saved under models and controllers folders respectively. Upon trying to establish a connection between them, I received an error stating "ng:areq ...

The Location header from the HTTPFound response does not contain any non-default port numbers

I am facing an issue with my Pyramid application setup. It is running on gunicorn, listening on a Unix socket behind nginx which is listening on port 8080. The problem arises when the Pyramid view returns HTTPFound(location='/'), the HTTP respons ...

Forming a distinct array from a collection of objects

Describing demoList: demoList = [ { id: 1, validFrom: "2019-06-01T00:00:00", validTo: "2020-06-17T00:00:00", xxxM: 50, xxxN: 2.2, xxxQ45: 2, xxxQ100: 1.65, xxxQ125: null, xxxQ150: null, xxxQ2 ...

Tips for implementing self-managed state in Vue.js data object

My approach in organizing my Vue application involves using classes to encapsulate data, manage their own state (edited, deleted, etc), and synchronize with the back-end system. However, this method seems to conflict with Vue in some respects. To illustra ...

Solutions for Utilizing Generic Mixins in Typescript

As a newcomer to Typescript, I have encountered an issue with mixins and generics. The problem became apparent when working on the following example: (Edit: I have incorporated Titian's answer into approach 2 and included setValue() to better showcas ...

Error: Platform core encountered a StaticInjectorError[t]: It is not possible to assign a value to the property '_injector', as it is undefined

This source code includes a rest API call and global variable reference. I have only utilized bootstrap CSS and omitted saving jQuery because bootstrap.js is not being used. After performing the (ng build -prod) command, I receive production build files ...

What is the best way to utilize a negative glob pattern?

After our build process completes, we end up with both e2015 and es5 bundles. For example, in the dist directory, you will find files like these: /common-es2015.7765e11579e6bbced8e8.js /common-es5.7765e11579e6bbced8e8.js /custom.js We are trying to set u ...

Angular does not adhere to globally defined styles

I have defined the margins for mat-expansion-panel in my styles.css file as follows: mat-expansion-panel { margin: 2vh; } Unfortunately, these margins will not be applied to my components unless they are also specified in the local CSS file. Even try ...

Choose only the options that are present in both arrays

I am working on creating a multiple select feature that displays all nodes, but only checks the ones that are present in 2 arrays. My front end is developed using Angular 8 and TypeScript. private mountSelect(nodesInRelation, lineApiKey) { console.lo ...

Steps to initiate a PDF file download when a button is clicked using Angular 6

I need assistance with downloading the .pdf file when clicking a button. Below is the code I am currently using: downloadMyFile() { const link = document.createElement('a'); link.setAttribute('target', '_blank&apos ...

The element is inherently an 'any' type as the expression of type 'number' does not have the capability to index type 'Object'

Hey there, I'm currently in the process of learning Angular and following along with the Note Mates tutorial on YouTube. However, I've hit a stumbling block as I attempt to implement sorting by relevancy. The issue lies with the code snippet belo ...

I am currently unable to retrieve any results for my fullcalendar tooltip

I am currently working on setting tooltips for events using Primeng's fullcalendar. Despite initializing the tooltip in the web console, I am unable to see it when hovering over an event. My development environment includes Typescript, Primeng 7.0.5, ...

Steps for managing files in Ionic Native: creating, reading, and writing them

Struggling to find proper examples for file operations like creating, reading, and writing text or logs into a file? I've done a lot of research but haven't stumbled upon any suitable solutions. The examples provided in this link seem helpful, ho ...