When I refresh the page in Angular2, the router parameters do not get loaded again

When loading my application on routers without parameters, everything is normal. However, when trying to use a router with params, the application fails to load.

For example: localhost:3000/usersid/:id

The code for the router is as follows:

const appRoutes: Routes = [
  { path: 'user', component: UserComponent },
  { path: 'info', component: InfoComponent },
  { path: 'users', component: UsersComponent },
  { path: 'usersid/:id', component: UsersIdComponent },
  { path: '', component: MainComponent },
  { path: '**', component: MainComponent }
];

Below is the component handling the params in the router:

import{Component} from '@angular/core'
import { ActivatedRoute } from '@angular/router';
import * as Datastore from 'nedb';

@Component({
  moduleId : module.id ,
  templateUrl : 'userid.component.html' ,
  styles : [`
    .SamRouter {
        overflow-y: auto;
    }
    `]
})

export class UsersIdComponent {
  id: any;
  private sub: any;
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
      this.sub = this.route.params.subscribe( params  => {
      // this.id = +params['id']; // (+) converts string 'id' to a number
      this.id = params['id'] || 0 ;

        // In a real app: dispatch action to load the details here.
     });
        console.log(  this.id )
   }
   ngOnDestroy() {
    //  this.sub.unsubscribe();
    }

}

Error Message:

http://localhost:3000/users/node_modules/bootstrap/dist/js/b‌​ootstrap.min.js Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3000/users/styles.css Failed to load resource: the server responded with a status of 404 (Not Found)

Answer №1

Configuring your server correctly is crucial depending on which server you are using. When a route does not exist, make sure to set up your server so that it redirects to index.html. If the server tries to find a file that doesn't exist when you press F5, it should automatically serve index.html first before letting the angular router take over.

Answer №2

Revise the below code snippet:

const appRoutes: Routes = [
  { path: 'user', component: UserComponent },
  { path: 'info', component: InfoComponent },
  { path: 'users', component: UsersComponent },
  { path: 'usersid/:id', component: UsersIdComponent },
  { path: '', component: MainComponent },
  { path: '**', component: MainComponent }
];

Update it as follows: (make sure to focus on the fourth element in the Routes array)

const appRoutes: Routes = [
  { path: 'user', component: UserComponent },
  { path: 'info', component: InfoComponent },
  { path: 'users', component: UsersComponent },
  { path: 'users/:id', component: UsersIdComponent },
  { path: '', component: MainComponent },
  { path: '**', component: MainComponent }
];

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

Unable to retrieve the value of a textbox located within a gridview

In my grid view, I have a textbox nested inside a TemplateField. I want to retrieve the value of this textbox when a button is clicked: This is where I create the textbox: <ItemTemplate> <asp:TextBox runat="server" ID="txtEmail" Text=&a ...

Learn how to hide the dropdown menu in Angular 8 by detecting clicks outside of the menu area

Is there a way to hide the custom dropdown menu whenever I click outside of it? After trying the code below, I noticed that it hides even if I click on an element inside the dropdown menu: <button class="btn btn-primary btn-sm mt-1" type="button" id= ...

What could be causing useEffect to trigger only after the component has been mounted in NextJS?

I'm currently encountering an issue with my implementation of a useEffect function that is supposed to act like a componentWillMount, but the behavior is not as expected. Within the code for Component (as demonstrated in the Codesandbox provided belo ...

Utilizing HTML to call a function and fetching data from AngularJS

I've been struggling to retrieve the value after calling a function in my HTML file. Despite trying various methods after conducting research, I have not achieved success yet. Take a look at the code below: HTML: <div class="form-group"> & ...

I am experiencing issues with the jQuery function within my MVC Application

When working on my MVC application, I encountered an issue where the onclick function was not functioning as expected. @section Scripts{ <script src="~/Scripts/plugins/toastr/toastr.min.js"></script> <script> $(document). ...

Updating an SVG after dynamically adding a group with javascript: a step-by-step guide

Currently, I am working on a circuit builder project using SVG for the components. In my HTML structure, I have an empty SVG tag that is scaled to full width and height. When I drag components from the toolbar into the canvas (screen), my JavaScript functi ...

Using Angular to retrieve data from a JSON file correlating with information in another JSON file

Just starting out with angular and facing a problem where I'm unsure of the best approach to setting up this code efficiently. I have 2 JSON files: images.json { "imageName": "example.jpg", "imageTags": ["fun","work","utility" ...

stepper vue with previous and next buttons

I am trying to create previous and next buttons in Vue, but I am struggling a bit because I am new to learning Vue. I have some methods like this.activeIndex < this.activeIndex - 1 that I need to implement. Can someone help me with how to do this? cons ...

How to minimize scaffolding with Redux, React, and Typescript?

Is there a way to avoid the process of instrumenting my Redux-Aware components? The level of scaffolding required seems excessive. Take, for instance, the minimal code necessary to define a redux-aware component: class _MyActualComponent extends React.Co ...

Utilize a Typescript library within a separate Typescript library

I have a TypeScript library on GitHub that I want to install using npm install --save git+ssh://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f38362b1d15c3f4">[email protected]</a>:User/mylib.git into my targ ...

Error: Attempting to assign value to the 'innerHTML' property of null in a Wordle clone with local storage

While developing a Wordle-inspired game for my website, I decided to utilize Local Storage to store the user's progress. Everything seemed to be working smoothly until an unexpected error occurred: "Uncaught TypeError: Cannot set properties of null (s ...

Encountered an issue locating the stylesheet file 'css/style.css' that is supposed to be linked from the template. This error occurred when trying to integrate Bootstrap with Angular

<link rel="stylesheet" href="plugins/bootstrap/bootstrap.min.css"> <link rel="stylesheet" href="plugins/owl-carousel/owl.carousel.css"> <link rel="stylesheet" href="plugins/magnific-pop ...

Access the most recent state value with React's Context API

Trying out the React context API, Take a look at the someComponent function where I pass the click event (updateName function) to update the value of state.name from the GlobalProvider function. After updating state.name, it reflects in the browser but t ...

Error encountered when attempting to create an index in ElasticSearch due to

I am encountering an issue with the elasticsearch npm module while attempting to create an Index, resulting in a TypeError with the following message: Unable to build a path with those params. Supply at least index The code snippet I am using is as follo ...

"Identify the protocol name (string) based on a specific port number in TCP/UDP communication

Is there a built-in function in any web-oriented language to return protocol names based on port numbers? For example, if we have the following code: protocol = get_protocol_name(22) print protocol We would expect it to print out "ssh". A more detailed ...

The difference between importing CSS in JavaScript and importing it directly in CSS lies in the way

Hello there, I am just starting out with web development and learning about Vue.js. In Vue 3, the recommended way to import CSS files from different packages is as follows: Method 1: Import directly in app.js //app.js import '../css/app.css'; i ...

When using Angular NGXS, calling `dispatch` method can lead to multiple

Currently, I am sending data from one component to be used in other components. However, I have noticed that when I dispatch the data, the subscribe function is being called multiple times. On a button click, I am dispatching the following: appStore.disp ...

Creating functional dropdown menus with popperjs in the latest Bootstrap version 5

Currently, I am attempting to implement dropdown menus in Bootstrap 5. According to my research, this feature requires Popper.js integration, but I am uncertain of the correct way to include it in my Laravel project that utilizes Laravel Mix. I have made ...

Unexpected glitch: three.js texture turns completely black

I am currently working on a simple geometry box that I want to decorate with a texture. However, the box seems to be invisible or completely black. This issue is related to a previous question that can be found here. Following the answer provided by gaitat ...

Enable automatic playback of HTML5 video with the sound on

I want to add an autoplay video with sound on my website, but I'm running into issues with newer browsers like Chrome, Mozilla, and Safari blocking autoplay if the video doesn't have a 'muted' attribute. Is there a clever HTML or Javas ...