Why does the page not work when I enter a certain URL with an ID parameter, and instead displays the error message "Uncaught ReferenceError: System is not defined"?

This is my "app.routing.ts":

import {provideRouter, RouterConfig} from "@angular/router";

import {DashboardComponent} from "./dashboard.component";
import {HeroesComponent} from "./heroes.component";
import {HeroDetailsComponent} from "./hero-details.component";

export const routes: RouterConfig = [
    {path: '',            component: DashboardComponent },
    {path: 'dashboard',   component: DashboardComponent },
    {path: 'heroes',      component: HeroesComponent },
    {path: 'details/:id', component: HeroDetailsComponent }
];

export const APP_ROUTER_PROVIDERS = [
    provideRouter(routes)
];

This is the page I wish to load by typing the URL:

import {Component, OnInit}  from "@angular/core";
import {Router, ActivatedRoute} from "@angular/router";

import {Hero}       from "./hero.class";
import {HeroService} from "./hero.service";

@Component({
    selector    : "my-hero-details",
    template    : `
        <div *ngIf="myhero">
            <h2>{{myhero.name}} details!</h2>
            <div><label>id: </label>{{myhero.id}}</div>
            <div>
                <label>name: </label>
                <input id="heroname" [(ngModel)]="myhero.name" placeholder="name">
            </div>
      </div>
      <button (click)="goBack()">Back</button>
    `,
    providers   : [HeroService]
})

export class HeroDetailsComponent implements OnInit{

    myhero:Hero;
    sub:any;

    ngOnInit(){
        this.getHeroDetails();
    }

    ngOnDestroy(){
        this.sub.unsubscribe();
    }

    constructor(private heroService:HeroService, private router:Router, private route:ActivatedRoute){}

    getHeroDetails(){

       this.sub = this.route.params.subscribe((param)=>{
           let id:number = +param["id"];
           //let id:number = +this.route.snapshot.params["id"];
           this.heroService.getHero(id).then((hero)=>{
               this.myhero = hero;
           });

        });

    }

    goBack(){
        window.history.back();
    }

}

A challenge arises when I enter the URL ".../details/12" with 12 as the ID. However, if I navigate to that page by clicking a button triggering the following code, it functions properly:

this.router.navigate(["/details", this.selectedHero.id]);

I'm not utilizing any server, instead, I am using "system.config.js" from Angular2 QuickStart, potentially causing an issue like "Uncaught ReferenceError: System is not defined".

Answer №1

Ensure that on the server side, you map your 404 route to match the possible routes in your Angular2 app, directing it to your Angular2 starting html file (such as index.html).

UPDATE1:

If using lite-server, any unmatched route should default to returning the index.html page:

When developing a single-page application, there are client-side routes that may not be recognized by the server. In such cases, when a route like /customer/21 is directly accessed before the Angular app is loaded, the server will return a 404 error as it does not have a matching route. To handle this scenario, the desired behavior is to serve the index.html file or any other defined starting page of the app. While BrowserSync lacks built-in support for fallback pages, lite-server offers custom middleware to address this issue.

You can specify the entry file using the "--entry-file=PATH" command line parameter to serve a specific file instead of a missing route:

live-server --entry-file=index.html

Refer to this question for more information: Angular 2.0 router not working on reloading the browser

You can also customize advanced behaviors using local bs-config.json or bs-config.js files.

For further details, visit: https://www.npmjs.com/package/lite-server

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

I'm baffled by the fact that my routes appear to be non-existent. I cannot comprehend the reason behind this issue

I'm fairly new to web development, and I've been struggling with this issue for the past hour. Even after simplifying my code to the bare minimum, it's still not working. Here's what I have so far: app.js: const express = require(&apo ...

Filter for the final item in Angular

Is there a way to create a filter that specifically retrieves the last element from a list? Alternatively, how can I implement a filter that excludes the last element? Context: I've got a list of items and I need to make sure the last item is editabl ...

What is the best way to enable the acceptance of a null value during the validation process of an optional

Currently, I am in the process of assembling a sandwich. Whenever all the necessary details are provided to Nest, everything operates smoothly and flawlessly. However, my predicament arises when attempting to assign null (empty string) to an enum, resultin ...

What is the best way to incorporate "thread.sleep" in an Angular 7 app within a non-async method like ngOnInit()?

Despite the numerous questions and solutions available on Stack Overflow, none of them seem to work when called from a component's init function that is not asynchronous. Here's an example: private delay(ms: number) { return new Promise( ...

Error in Mocha test: Import statement can only be used inside a module

I'm unsure if this issue is related to a TypeScript setting that needs adjustment or something else entirely. I have already reviewed the following resources, but they did not provide a solution for me: Mocha + TypeScript: Cannot use import statement ...

Angular toolbar on the left side that hovers seamlessly

1 I am using Angular Material toolbar and trying to position a span inside the toolbar on the left side. I have attempted using CSS float left, but it is not working. Can anyone provide some assistance please? <mat-toolbar> <span>le ...

Utilizing REST-API with Angular 2 and Electron

I am encountering an issue with my Electron App that utilizes Angular 2. I had to make a modification from <base href="/"> to <base href="./">, which is a relative path within the file system, in order to make it function properly. However, thi ...

Tips for successfully passing an Observable identifier to mergeMap

Monitoring the outputs of a list of observables with mergeMap is straightforward, as shown in this example code snippet: export class TestClass { test() { const observableA = of(1, 2, 3); const observableB = of(7, 3, 6); const observableC = ...

What is the best way to invoke a method within the onSubmit function in Vuejs?

I am facing an issue with a button used to log in the user via onSubmit function when a form is filled out. I also need to call another method that will retrieve additional data about the user, such as privileges. However, I have been unsuccessful in makin ...

Solution for accessing the callee function in JavaScript slide down operation

While exploring a tutorial from CSS Tricks about animating section height, I came across a solution that I would like to implement in my Angular 2 application. Here is the function responsible for expanding sections in my app: expandSection(element) { / ...

Struggling with "Content" not being recognized in Typescript PouchDB transpilation errors?

I have been diligently working on an Ionic app for the past three months with no major issues during development or deployment to mobile devices. However, yesterday I encountered a frustrating NPM dependency problem while trying to deploy to mobile. In an ...

Properly specifying the data type for a generic type variable within a function in TypeScript

As I work on my express project, I am currently coding a function called route. const morph = (params: Function[]) => (req: Request) => params.map(f => f(req)) const applyTransformers = (transformers: Function[]) => (response: any) => { ...

"Experience the power of utilizing TypeScript with the seamless compatibility provided by the

I'm attempting to utilize jsymal.safeDump(somedata). So far, I've executed npm install --save-dev @types/js-yaml I've also configured my tsconfig file as: { "compilerOptions": { "types": [ "cypress" ...

Exploring ASP.Net Core features: IApplicationBuilder.Map for routing, serving SPA, and managing static

I am exploring the use of Asp.Net Core 2.2 to host my Angular application and handle API requests (on /api). In my Startup.cs file, specifically in the Configure method, I have configured it as follows: app.Map("/home", config => { ...

What is the best way to recycle a variable in TypeScript?

I am trying to utilize my variable children for various scenarios: var children = []; if (folderPath == '/') { var children = rootFolder; } else { var children = folder.childs; } However, I keep receiving the following error message ...

angular displaying incorrect values for counter

Hi there, I am new to using Angular and I'm currently facing an issue with increasing and decreasing product quantity on the cart page. The problem is that in my first index it works fine, but in the second index, the value starts with the first index ...

A unique column in the Foundry system that utilizes function-backed technology to calculate the monthly usage of engines over a

In my dataset of ‘Engine Hours’, I have the following information: Engine# Date Recorded Hours ABC123 Jan 21, 2024 9,171 ABC123 Dec 13, 2023 9,009 ABC123 Oct 6, 2023 8,936 XYZ456 Jan 8, 2024 5,543 XYZ456 Nov 1, 2023 4,998 XYZ456 Oct 1 ...

I am facing an issue with calling a controller from an HTTP GET request in ASP.Net Core 6 using a Single Page Application (SPA) endpoint

[UNSOLVED] - Seeking help from developers [Issue] As a newcomer to the industry, I apologize for my lack of experience in advance. I am currently facing a challenge with ASP.Net Core 6 and it seems like I am missing something simple, but I can't see ...

Is it possible to assign a property value to an object based on the type of another property?

In this illustrative example: enum Methods { X = 'X', Y = 'Y' } type MethodProperties = { [Methods.X]: { x: string } [Methods.Y]: { y: string } } type Approach = { [method in keyof Method ...

Display a loader while waiting for an API call to complete within 5 seconds using Angular and RxJS operators. If the API call takes longer

We are actively working to prevent user blockage during file uploads by implementing a method in Angular using RxJS. How can I display a toastr message and hide the loader if the API does not complete within 5 seconds? uploadFile() { this.service.uploa ...