Issue: Angular 7 unable to route directly to URL with specific ID

When I click on the navigation link with code for button click, it works perfectly fine:

this.router.navigate(['/dashboard', this.selectedDateString]);

However, if I manually type the URL into the address bar like this:

I receive a

forbidden!

message. Why does routing work when triggered from within the app but not when directly typed into the address bar?

This is my routing module setup:

const appRoutes: Routes = [
  { path: 'dashboard/:date', component: DashboardComponent },
  { path: 'dashboard', component: DashboardComponent },     
  { path: '',   redirectTo: '/dashboard', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      appRoutes, { onSameUrlNavigation: 'reload' }
    )
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule {}

Answer №1

I concur with @TheHeadRush.

It seems like your server is not set up to handle frontend routes by returning the base document from those endpoints.

If you prefer not to have the server handle this, you can configure Angular to use the HashLocationStrategy, which uses hash fragments for page navigation.

Instead of http://myapp/dashboard/01152020, your URL will appear like this in the browser http://myapp#/dashboard/01152020

You need to provide it in your root app module like this.

@NgModule({
  imports: [
    BrowserModule,
    MyFeatureModule,
  ],
  providers: [
    {
      provide: LocationStrategy, useClass: HashLocationStrategy,
    },
  ]
})
export class AppModule {}

Answer №2

To test it out, experiment with using the html and implementing the <a> tag along with a router link as demonstrated below:

      <a [routerLink] = "['dashboard', selectedDateString]" href="javascript:;"></a>

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

Support different response types when making nested API calls

When working with two API calls that return different responses, one typed as TestData1Res and the other as TestData2Res, how can I handle the scenario where the response could be either type and process the property? `TestData1Res{ testData: string } Te ...

What is the best way to set up initial state in react-native-day-picker?

I have been experimenting with implementing react-native-calendar into my project. Here is the code snippet I am working on: import React from 'react'; import {Calendar} from 'react-native-day-picker'; const MyCalendar = () => { ...

Express encounters difficulty in processing Chunked Post Data

I am currently retrieving data from a Campbell Scientific data logger. This data is being posted to an application that is coded in Typescript using Express and BodyParser. The request successfully reaches the app (as I'm able to debug it), however, t ...

In the home page, I want my navigation bar to have a transparent background, but in all other pages, I prefer a white background

Is there a way to make the navigation bar transparent only on the home page, and have a white background on all other pages? I attempted to achieve this using Angular, but it did not work as expected. Here are snippets of my code: navbar.component.html & ...

Limitation for class instance, not an object

Is it possible to implement type constraints for class instances only in TypeScript, without allowing objects? Here is an example of what I am trying to achieve: class EmptyClass {} class ClassWithConstructorParams { constructor (public name: string) ...

What steps should be taken to enable SCSS in Jest for unit testing in TypeScript Next.js?

I am facing an issue with the scss import in my project. I have attempted to solve it by using mockup and identity-obj-proxy, but neither of them seems to work. I suspect that there might be a problem with my regex expression. The specific error arises fr ...

conditional operator that compares values in router events

As I examine an object, links = { link1: 'page1', link2: 'page2', link3: 'page3', link4: 'page4', link5: 'page5', link6: 'page6' } I possess a function for retrieving t ...

What is the reason behind the narrowing of the type by indexing into a mapped type?

This question is inspired by an amazing answer found here: My curiosity lies in why the indexing works in the mapped type trick. Let's illustrate with an example: type MyData = { a: { alpha: string; }; b: { beta: number; } } type ...

Oops! We encountered an error: Uncaught (in promise): [object Object]. Angular 5 version is

Trying to implement an upload button using Angular 5, I have the following code in my .ts file: handleFiles(e) { this.file = e.srcElement.files[0]; if (this.file.size > 2097152) { let snackBarRef = this.snackBar.open('Images must ...

Learning to handle data fetching and looping in NextJs

I'm facing an issue with fetching data through a loop in getStaticProps. The array ends up empty due to asynchronous code. If I pass the ID array and implement the logic within the React component, it works fine. Should I continue using the component ...

Developing an asynchronous function to retrieve data from an external API utilizing Await/Async strategy

Currently, there is a method under development that retrieves a value from the API. What steps are needed to properly integrate Async/Await functionality into this process? fetchAccountById(){ let accountName; this.accountService.fetchDa ...

The responsive table fails to completely fill the column it is contained within

In my Angular application, I am integrating Bootstrap 4. Within one of the component's HTML files, I am attempting to embed a responsive table within a grid row. I have followed the instructions by nesting the "table" div inside another div with the ...

Unlocking the Secret: How to Bind a Global Touch Event Handler in Angular 4 to Prevent iOS Safari Page Drag

The issue at hand is that within my Angular 4 application, there is a D3.js chart that relies on user touch input for dragging a needle to a specific value. The drag functionality is triggered by 'touchstart', while the registration of the final ...

Subtracting Arrays Containing Duplicates

Imagine having two arrays defined like this: const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr'] const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa&ap ...

Exclude Cancel button solely from pFileUpload

While using pFileUpload, I am able to see all three buttons, however, I do not require the Cancel button. Even though the documentation mentions an attribute called showCancelButton, applying it does not result in any changes. <p-fileUpload name="demo ...

Unable to pass a component property to a styled Material-UI Button

I have customized a MUI Button: const SecondaryButton = styled(Button)<ButtonProps>(({ theme }) => ({ ... })); export default SecondaryButton; When I try to use it like this: <label htmlFor="contained-button-file"> <input ...

Project encapsulating Angular 2 Functionality

I am tasked with creating an angular 2 application that acts as a wrapper for multiple other angular 2 applications. Let's call the main module of the project MainModule. There are also third-party modules such as AppModule1, AppModule2, etc., which ...

The TSX file is encountering difficulty rendering an imported React Component

Upon attempting to import the Day component into the Week component (both .tsx files), an error is thrown: Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. ...

The 'Component' binding element is assumed to have an unspecified 'any' type in TypeScript

Hello, I'm new to coding and encountering an issue with the code below. My goal is to create a protected "Dashboard" page, but I keep getting a binding error that says: Binding element 'Component' implicitly has an 'any' type.ts( ...

ag-Grid incorporating new style elements

For my Angular application, I have a simple requirement of adding a CSS class when a row expands or collapses to highlight the row. I attempted to use gridOptions.getRowClass following the documentation at https://www.ag-grid.com/javascript-grid-row-styles ...