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

Discover the best method for retrieving or accessing data from an array using Angular

In my data processing task, I have two sets of information. The first set serves as the header data, providing the names of the columns to be displayed. The second set is the actual data source itself. My challenge lies in selecting only the data from th ...

Solution for accessing the callee function in JavaScript slide down operation

While exploring a tutorial from CSS Tricks about animating section height, I came across a solution that I would like to implement in my Angular 2 application. Here is the function responsible for expanding sections in my app: expandSection(element) { / ...

The CloudWatch logs for a JavaScript Lambda function reveal that its handler is failing to load functions that are defined in external

Hello there, AWS Lambda (JavaScript/TypeScript) is here. I have developed a Lambda handler that performs certain functions when invoked. Let me walk you through the details: import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda' ...

Using webpack to bundle node_modules into your application

I am facing an issue while trying to load some modules like: moment echarts In my package.json file, I have the following versions specified: "echarts": "^3.1.10" "moment": "^2.14.1" However, I am encountering the errors below: VM2282:1 Uncaught Ref ...

What is the most effective method to create a versatile function in Angular that can modify the values of numerous ngModel bindings simultaneously?

After working with Angular for a few weeks, I came across a problem that has me stumped. On a page, I have a list of about 100 button inputs, each representing a different value in my database. I've linked these inputs to models as shown in this snipp ...

Ways to specify an unused parameter within a function

As I work on my code, I encounter the need to separate the key and value from a request params object in order to validate the value using ObjectID. To achieve this, I decided to iterate over an array of entries and destructure the key and value for testin ...

Discover the step-by-step guide to implementing pagination using NG-ZORRO-Andt in your Angular

I am currently using NG-ZORRO Ant Design pagination on my HTML page and it is displaying correctly in my browser. However, I am struggling with linking the data from the API to the pagination feature. Here is the snippet of my HTML code: <div class ...

Approach to streamlining and making services more flexible

Currently, I am immersed in a complex Angular 2 endeavor that requires fetching various types of objects from a noSQL database. These objects are represented using straightforward model classes, and I have set up services to retrieve the data from the DB a ...

What is the most effective method for comparing and updating objects within arrays or lists in frontend Angular applications using TypeScript?

While I acknowledge that this approach may be effective, I am of the opinion that there exists a superior method to accomplish the same goal I have two separate lists/arrays containing distinct objects, each with a common attribute. My objective is to ite ...

The Angular2 module x.module does not contain the exported member NavComponent

Encountering difficulties with rc.5 of Angular2. I have created an NgModule named xModule where I define NavComponent and export it. This is specified in the file x.module.ts. However, when attempting to import xModule into yModule and export NavComponent ...

There was an unexpected error: The development server's address information is not defined

Whenever I attempt to utilize ng serve with SSL and a custom hostname, I encounter the error message "An unhandled exception occurred: Dev-server address info is not defined." Has anyone found a solution to this issue? Here is the command I am using: ng s ...

Navigating to a component that also needs to redirect

I have a main feature (let's call it "main hub") that houses various sections. Within the "main hub" feature, I navigate to another section (let's call it "subsection") which also contains different subsections. In one of these subsections, call ...

What is the method for utilizing enum values as options for a variable's available values?

I'm curious about using enum values in TypeScript to restrict the possible values for a variable. For example, I have an enum named FormType with Create and Update options. Is there a way to ensure that only these enum values are used? enum FormType { ...

Tips on utilizing storage.set() within google.maps.events.addListener(marker, 'dragend', function() { }); in Ionic 3

google.maps.event.addListener(Marker, 'click', (function(Marker) { return function() { this.storage.set('mylocation', this.Marker.getPosition()); } })(Marker)); polyfills.js:3 Uncaught TypeError: Cannot read property 'set ...

Alert for timeout triggered without any error logs recorded

While working on a login & register page, I encountered an issue. After clicking the register button, a timeout alert error appeared despite no log errors being present. However, the data used to register was successfully saved in the MYSQL database. ...

What is the method for placing a title in the initial column with the help of v-simple-table from Vuetify.js?

I am interested in using the v-simple-table UI component from Vuetify.js to create a table similar to the one shown below. After creating the code in codesandbox and previewing the output, I noticed that the title is not aligned properly. HTML↓ < ...

leveraging the import statement in conjunction with SystemJs

Currently, I am in the process of creating a sample code using TypeScript and SystemJS for the browser. In my app.ts file: import {Person,add as test} from './testLib' In the generated app.js file (by TypeScript compiler): var testLib_1 = re ...

Fastest method to invoke a potentially undefined function

With a background in C#, I am familiar with the null-conditional operator which allows you to call a function while avoiding a potential null-reference exception like this: Func<int> someFunc = null; int? someInteger = someFunc?.Invoke(); // someInte ...

Error in Ionic: Although $state.go successfully changes the URL, the corresponding view fails to load

When attempting to change the state programmatically, the URL updates, but the view does not load. It only works after refreshing the page, however using $window.location.reload(true); feels unconventional. Controller myApp.controller('WelcomeContro ...

Executing a method with parameters in ngOnInit in Angular - A simple guide

Is it feasible to trigger a parametrized method in ngOnInit within the same component? I currently have an onclick(p.key) function in the html file, defined in the corresponding typescript file. However, my aim is to invoke it during ngOnInit. Is this achi ...