Eliminate the hashtag (#) from the URL in Angular 11

I am facing an issue with removing the # from the URL. When I try to remove it, the application encounters a problem upon deployment to the server. Upon page refresh, a 404 error status is returned.

For instance:

https://example.com/user/1 (works)

https://example.com/user/2 (does not work)

In app-routing.module.ts:

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  providers: [
    {provide: LocationStrategy, useClass: PathLocationStrategy} 
  ],
  exports: [RouterModule]
})

In app.module.ts:

......
providers: [ Location, {provide: LocationStrategy, useClass: PathLocationStrategy}]

I would appreciate any guidance on how to resolve this issue.

Answer №1

PathLocationStrategy is the default location strategy of Angular Routing, which effectively resolves the hash(#) issue.

No errors are present in your code; please review the following points:

  1. RouterModule.forRoot(routes, { useHash: true }) //ensure that "useHash" parameter is not included
  2. providers: [ // The line below is optional as the default LocationStrategy is PathLocationStrategy {provide: LocationStrategy, useClass: PathLocationStrategy} ]

If you encounter problems only when deployed on a server, ensure that the entry point configuration on the server points to index.html file.

NOTE: With PathLocationStrategy, configure your web server to serve index.html (the app's entry point) for all requested locations.

Check for the presence of <base href="/"> in index.html and make sure that the backend server renders the index.html file based on the path.

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

Having trouble getting a local npm installation to work from a specific file path?

After following the instructions from this helpful link to install an npm package through a file path, I encountered an error when attempting to use it: Cannot find module '<module_name>' or its corresponding type declaration Are there an ...

How can I call a method from a class using Typescript when getting an error saying that the property does not exist on the

Below is a service definition: export class MyService { doSomething(callbacks: { onSuccess: (data: Object) => any, onError: (err: any) => any }) { // Function performs an action } } This service is utilized in a component as shown be ...

What is the best way to incorporate cors modules in TypeScript?

I am encountering some difficulties while attempting to import the cors module in a TypeScript project using Express. When I use the following code: import cors from "cors"; I receive the following error message: "Cannot find module &apos ...

The lazy loading feature in Angular 12 is not functioning correctly for path modules

My application has a jobs module with various components, and I'm trying to lazy load it. However, I've encountered an issue where accessing the module through the full path http://localhost:4200/job/artist doesn't work, but accessing it thr ...

A step-by-step guide on reading/loading a JSON file using Typescript

I'm fairly new to Typescript and I'm attempting to parse a simple JSON file using Typescript. After searching online and testing different solutions, I still haven't been able to find a straightforward code snippet that reads a local JSON fi ...

Encountering problems with TypeScript in a Node application when using the package manager

I am facing an issue while trying to package my node app into an exe using "pkg". I work with TypeScript, and when I attempt to run pkg index.ts --debug, an error pops up. Node.js v18.5.0 Warning Failed to make bytecode node18-x64 for file /snapshot/ ...

Utilizing ExpressJS in a NodeJS application with ES6 and Typescript

After confirming my information, I discovered that in an ES6 application, it is necessary to import dependencies using import .. from '..' instead of var .. = require('..'). I made the necessary changes to the imports, but encountered ...

Leverage the capabilities of mat-datepicker independently without relying on an

Is it possible to have the datepicker located in a fixed sidebar that is always visible and not linked to an input field? My idea was to include the component and set opened = true so that the datepicker remains in a box that is constantly displayed. ...

What is the reason for the ngFor loop in Ionic 5 component not functioning properly?

I'm facing an issue with the *ngFor directive in one of my components. It's strange because it works fine in other components. Can anyone help me figure out what I might be doing wrong? @Component({ selector: 'app-age-picker', temp ...

Tips for updating a reactive form with multiple layers of nested JSON values

I am tasked with retrieving and working with the data from a deeply nested (potentially infinite levels) reactive form that includes formArrays, formGroups, and formControls. This data is stored in a database. Currently, my approach involves patching the ...

Ensure that missing types are included in a union type following a boolean evaluation

When working with typescript, the following code will be typed correctly: let v: number | null | undefined; if(v === null || v === undefined) return; // v is now recognized as a `number` const v2 = v + 2; However, if we decide to streamline this process ...

The option value in mat-autocomplete is not displaying correctly on IOS devices

When I click on the first option in the dropdown menu, it does not display the selected option in the field. However, when I select the second option, then the value of the first option appears, and when I choose the third option, the value of the second o ...

Modify the innerHTML to adjust font size when a button is clicked in Ionic 5, or eliminate any unnecessary spaces

I have been experimenting with changing the font size of a variable in .html when the variable contains whitespace. In my .ts page, I use the following code to remove the whitespace: this.contents = this.sanitizer.bypassSecurityTrustHtml(this.product[&apos ...

Creating a FormGroup dynamically using an observable: A step-by-step guide

My current project involves creating a page with multiple reactive forms, tailored for different countries. These forms are generated based on JSON arrays received from the backend, allowing users to view and update settings individually. As I am uncertain ...

Differences Between APP_INITIALIZER and platformBrowserDynamic with provide

I've discovered two different approaches for delaying an Angular bootstrap until a Promise or Observable is resolved. One method involves using APP_INITIALIZER: { provide: APP_INITIALIZER, useFactory: (configService: ConfigurationService) => ( ...

Using AngularJS $resource to send query strings instead of JSON objects in a POST request (Typescript)

Whenever I create a custom $resource action like this: getEntityResource(): ng.resource.IResourceClass<IEntityResource> { let addAction: ng.resource.IActionDescriptor = { method: 'POST', url: 'http://l ...

Exploring the capabilities of SWR for updating data in Next JS

I have been working on creating a component with an active property that can be toggled by the user as many times as they want. Since I am using Next.js, I decided to implement SWR for client-side rendering. However, despite my efforts over the past few da ...

Version 2.0.0 of Angular working with Karma to offer Router capabilities

When a test requires an instance of the `Router`, simply providing the `Router` itself is not sufficient: import {Router} from '@angular/router'; import {it, inject, beforeEachProviders} from '@angular/core/testing'; import {Compo ...

A step-by-step guide to resolving the TS2345 compilation error during your TypeScript upgrade from version 4.7 to 4.8

We encountered a compiling error after upgrading from TypeScript 4.7.4 to a newer version (specifically, 4.8.4). This error was not present in our codebase when using 4.7.4. To pinpoint the issue, I have extracted the error into a small code snippet. When ...

I am struggling to comprehend the concept of dependency injection. Is there anyone available to provide a clear explanation for me?

I am working on a NestJS application and trying to integrate a task scheduler. One of the tasks involves updating data in the database using a UserService as shown below: import { Injectable, Inject, UnprocessableEntityException, HttpStatus, } fro ...