Angular 16 routing not loading content

I configured the routes in Angular v16 and encountered a blank page issue with the login and register functionality. I suspect it has to do with routing, but after checking multiple times, I couldn't pinpoint the exact problem. Below are snippets of the code:

Here is the access service implementation:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import {Login} from "../../model/login";
import {Register} from "../../model/register";
import { JwtHelperService } from '@auth0/angular-jwt';

@Injectable({
  providedIn: 'root'
})
export class AccessService {
  private baseUrl = 'http://localhost:8096';

  constructor(private http: HttpClient, private jwtHelper: JwtHelperService) { }

  login(loginData: Login): Observable<any> {
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    return this.http.post(`${this.baseUrl}/login`, loginData, { headers });
  }

  register(registerData: Register): Observable<any> {
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    return this.http.post(`${this.baseUrl}/customerRegister`, registerData, { headers });
  }

  saveTokens(tokens: { jwtToken: string, refreshToken: string }): void {
    localStorage.setItem('jwtToken', tokens.jwtToken);
    localStorage.setItem('refreshToken', tokens.refreshToken);
  }

  getJwtToken(): string | null {
    return localStorage.getItem('jwtToken');
  }

  getRefreshToken(): string | null {
    return localStorage.getItem('refreshToken');
  }

  removeTokens(): void {
    localStorage.removeItem('jwtToken');
    localStorage.removeItem('refreshToken');
  }

  isTokenExpired(): boolean {
    const jwtToken = this.getJwtToken();
    return jwtToken ? this.jwtHelper.isTokenExpired(jwtToken) : true;
  }
}

Below you can find the application routes configuration:

export const routes: Routes = [
  { path: '', redirectTo: '/main', pathMatch: 'full' },
  // Define all other paths here
];

Lastly, here is the register component implementation:

@Component({
  selector: 'app-register',
  standalone: true,
  imports: [CommonModule, FormsModule, HttpClientModule],
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent {

  constructor(private accessService: AccessService, private router: Router) { }

  onSubmit(registerData: Register): void {
    // Handle registration logic here
  }
}

I have verified the connection to the backend API and confirmed that the issue lies within the Angular setup rather than the backend. Additionally, I am trying to retrieve endpoints from the backend API.

Answer №1

You are facing a dependency issue that requires importing the HttpClientModule in your standalone component.

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [CommonModule, HttpModuleClient], // Make sure to import necessary modules here
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

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

Incorporating DefinitelyTyped files into an Angular 2 project: A step-by-step guide

I am currently developing an application using angular 2 and node.js. My current task involves installing typings for the project. In the past, when starting the server and activating the TypeScript compiler, I would encounter a log with various errors rel ...

A data type labeled as 'undefined' needs to include a method called '[Symbol.iterator]()' which will then return an iterator

I've been working on converting my reducer from JavaScript to TypeScript, but I keep encountering a strange error that I can't seem to resolve. The issue arises when I attempt to use ellipsis for array deconstruction in the reducer [...state.mess ...

The specified 'Promise<Modules>' type argument cannot be assigned to the parameter of type '(params: any) => Promise<Modules>' in the current context

Looking for some help with this helper function that I need to call, it has the following signature: export const fetchPaginated = async <T>( callback: (params: any) => Promise<T>, { page = 1, pageSize, }: { page?: number; page ...

Creating a global user object accessible to all Angular2 components

Hey there! I've successfully shared the Parent container's property with an attribute directive and inputs, but it's not working when the child component is brought in using <router-outlet>. Any suggestions on how to share it with ever ...

What is the method for extracting children from a singular object in json-server rather than an array?

I am currently utilizing json-server as a mock-backend to fetch child data from a single object. The main table is called sentinel and the secondary table is named sensor It can be observed that sensors is an array, while sentinel is an object. I have ...

How can I upload a file with MeteorJS?

(Originally posted on the Meteor forums) Imagine wanting to transfer a file from one computer to a server powered by Meteor through HTTP when the second computer triggers a specific API. I successfully built an application for this purpose using NodeJS, ...

Using a dropdown list to filter values in a table with Angular ngBootstrap

Seeking assistance with filtering table values based on the selected filter. I plan to utilize this ngbDropdown as my filter. If I choose company A, only entries related to company A will be displayed in the table. I am unsure about how to connect the f ...

What is the best Node version for me to use?

When downloading Node, you are given the option of choosing between LTS and Current versions. The LTS version is 4.6.0, while the current version is 6.7.0. I opted for the LTS version, which comes bundled with npm version 2.15.9. However, I encountered a ...

Angular Material Tree View with Text Labels Only

I have been researching Angular Material Tree Views and noticed that most examples use icons for expanding or retracting child nodes. I'm curious if anyone has any examples of implementing the Material Tree View where clicking on the parent text expan ...

understanding the life cycle of components in Ionic

I created a component with the following structure: export class AcknowledgementComponent implements AfterViewInit { private description: string; @Input('period') period: string; constructor() { } ngAfterViewInit() { console.log ...

Express.js using GET request to retrieve all data entries from the database

I am facing a challenge in retrieving specific user data using the GET method on Express.js through a Form. Instead of returning only one user's information, it is currently returning all values when the form is used. Here is the code from index.html ...

Display data in a template upon receiving a response from the server

Hello, I am currently in the process of developing my very first Angular application and could use some assistance. Specifically, I am working on a component that serves as an image search box. When a user inputs a search query, a request is sent to an API ...

In Java, handle request bodies in XML or JSON without resorting to String manipulation

In my current project utilizing Spring Boot and Java, I am faced with the challenge of calling multiple external services. Each of these services requires a complex JSON or XML body as input, with varying fields that may not always be required. Here are so ...

The API request does not provide randomized results and does not show any display

I am facing an issue with a button that is supposed to fetch a random user from an API. When I retrieve all the users, the information is displayed correctly. However, when I try to select a user at random, it does not work as expected. Also, it seems to a ...

ng-select search functionality failing to display any matches

Currently, I am encountering an issue with the ng-select functionality in my Angular CLI version 11.2.8 project. Despite using ng-select version 7.3 and ensuring compatibility with the Angular CLI version, the search functionality within the select eleme ...

How can I load a separate component.html file using a component.ts file?

Hey there, I'm a beginner with Angular and I have a question about loading a different home.component.html file from a method within books.component.ts. Here's the code snippet from my books.component.ts file: import { Component, OnInit } from ...

Utilizing puppeteer-core with electron: A guide

I found this snippet on a different Stack Overflow thread: import electron from "electron"; import puppeteer from "puppeteer-core"; const delay = (ms: number) => new Promise(resolve => { setTimeout(() => { resolve(); }, ms); }) ...

Tips on concealing the scrollbar only when a particular element is visible

I inserted the following code into my index.html file: <head> <style> body::-webkit-scrollbar { display: none; } </style> </head> This code successfully hides the scrollbar. My goal is to only h ...

What is Prettier's reasoning for suggesting the use of `;` before a destructuring assignment declaration?

I am facing an issue with the if block within my Angular component: if (desc.length > 0) { [this.errorMsg] = desc } The problem arises as Prettier suggests adding a ; at the start of the destructuring assignment: if (desc.length > 0) { ;[thi ...

Tips on setting the first root element to automatically expand in a tree component

Currently, I am utilizing a tree component that includes partially loaded data. For reference, here is the link to the stackblitz example: StackBlitz. Is there a way for me to have the child element of the first root element automatically opened by defau ...