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

Utilizing JavascriptExecutor in Selenium Webdriver to start playing a video

Is it possible to trigger the play function in a page's JavaScript jQuery code using JavascriptExecutor? Below is an example of code extracted from a website: <script type="text/javascript"> jQuery(document).ready(function($) { $('#wp_mep ...

Could there be a scenario where the body onload function runs but there is still some unexec

I am feeling confused by a relatively straightforward question. When it comes to the <body> tag being positioned before content, I am wondering about when the body onload function actually runs - is it at the opening tag or the closing tag? Additio ...

The styles from the npm package are not being properly applied to the class

After creating my react npm package using webpack, I encountered an issue where the styles from the package were not being applied to classes when installed in my react project. I used style-loader in my webpack configuration, but kept getting errors sayin ...

Steps for launching Angular 5 application using Node.js server

I have developed an Angular 5 application that retrieves data from a node.js server. I successfully deployed the application to my web server hosted by FastComet, which supports node.js, but unfortunately, the server does not seem to be functioning properl ...

The map failed to display any information

<div> {!props.isLoading && <div> {normalizedData.map((outerObj,index) => { { <p className="space_name"> {outerObj.space_name} </p> ...

Converting "require" to ES6 "import/export" syntax for Node modules

Looking to utilize the pokedex-promise for a pokemonapi, however, the documentation only provides examples on how to require it in vanilla JavaScript: npm install pokedex-promise-v2 --save var Pokedex = require('pokedex-promise-v2'); var P = new ...

Exploring the Possibilities of Wordpress Search with Multiple Dropdown Options

Is it possible to search across multiple categories? For example, I have 4 dropdown menus: 1. City 2. Area 3. Month 4. Products/Services When a user visits my site, they will see a static page with 4 dropdown lists and a "search" button. After the user ...

What would be the ideal alternative if the Google Ajax API is unavailable, given that Google does not allow for local installation?

On my website, I include the following script: ... <script type="text/javascript" src="https://www.google.com/jsapi"></script> ... This particular script is from Google and is used to dynamically load other resources, such as the Google Chart ...

React state not being updated by setState method

Here's the situation: let total = newDealersDeckTotal.reduce(function(a, b) { return a + b; }, 0); console.log(total, 'tittal'); //displays correct total setTimeout(() => { this.setState({ dealersOverallTotal: total }); }, 10); cons ...

Error: The specified updateTag type in the Angular SEO service is not compatible

I am in the process of developing an SEO service using Angular's Meta service (https://angular.io/api/platform-browser/Meta) Within the service, there is a method for managing social media tags that seems to be encountering issues and producing the f ...

Changing the size on click using Jquery

I'm attempting to make a button shrink another element using jQuery. Here's what I have so far: $( "#img1" ).click(function() { $("#img2").css("-moz-transform:scale", "0.7, 0.7"); }); However, this solution doesn't seem to be functio ...

A guide to accessing the currently hovered element on a Line Chart with Recharts

Just diving into this community and also new to ReactJS :( https://i.stack.imgur.com/k682Z.png I'm looking to create a tooltip that displays data only when hovering over the value 1 line. Unfortunately, the current tooltip is not behaving as expecte ...

Understanding the document.domain feature in Javascript

I have a website called foo.com hosted on server bar. Within this website, I have created a subdomain called api.foo.com. To connect the subdomain with Google Apps, I have set up a CNAME entry pointing to ghs.google.com. Now, I am facing an issue when att ...

Verify and deselect boxes

Can someone help me with checking and unchecking checkboxes? I'm facing a lot of issues with it. You can find my code snippet here: http://jsfiddle.net/N5Swt/: <input type="checkbox" id="checkbox1" /> <span> Check me! </span> // ...

Utilize Electron's fs to stream a file directly to an HTML video player while it is being downloaded

I am currently exploring the possibility of using the HTML video player to stream a file from the file system within Electron. My goal is to initiate streaming while the file is still being downloaded. I am uncertain whether my current approach will be ...

Using react-hook-form for form submission and managing state in React

I want a button that toggles between displaying "Edit" for entering Edit mode and "Save" for submitting the form. However, the issue is that when I press the button while it shows "Edit," it submits the form. Link to codesandbox with the code provided be ...

Converting Angular 2/TypeScript classes into JSON format

I am currently working on creating a class that will enable sending a JSON object to a REST API. The JSON object that needs to be sent is as follows: { "libraryName": "temp", "triggerName": "trigger", "currentVersion": "1.3", "createdUser": "xyz", ...

Updating a section of a webpage using jQuery Mobile

I'm currently facing an issue with modifying a specific section of my webpage. Although this problem has been discussed before, I haven't found a satisfactory solution yet. The element in red on the page needs to change dynamically based on the ...

What is the proper way to mention JavaScript packages when including them as parameters in Angular elements within HTML?

I was looking to enhance the command to be more authoritative. <div (click)="lastCall(999)">click me</div> My attempt to utilize Number.MAX_SAFE_INTEGER resulted in an error from my computer stating that it wasn't recognized. As a result ...

The specified "ID" type variable "$userId" is being utilized in a positional context that is anticipating a "non-null ID" type

When attempting to execute a GraphQL request using the npm package graphql-request, I am exploring the use of template literals. async getCandidate(userId: number) { const query = gql` query($userId: ID){ candidate( ...