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

Should an HTML canvas in Angular be classified as a Component or a Service?

I have a basic drawing application that uses an MVC framework in TypeScript, and I am looking to migrate it to Angular. The current setup includes a Model for data handling, a View for rendering shapes on the canvas, and a Controller to manage interactio ...

Is there any distinction between using glob wildcards in the tsconfig.json file when specifying "include" as "src" versus "include" as "src/**/*"?

Is there a distinction between these two entries in the tsconfig.json file? "include": ["src"] "include": ["src/**/*"] Most examples I've come across use the second version, but upon reviewing my repository, ...

Resetting the forms as users navigate between different tabs on the mat

I am currently working on an Angular application and I would like to incorporate mat-tabs. However, I am facing an issue where every time I switch between tabs, the inputs in each tab are resetting to empty values. Here is the HTML code snippet: <mat- ...

Managing event date changes in Angular PrimeNG FullCalendar

Is there a way to capture an event when the date of an event is changed? I would like to receive the new date in a function. Is this functionality possible? For example, if I have an event scheduled for 2020-01-01 and I drag it to date 2020-01-10, how can ...

Tips for updating property values when calling a TypeScript function

Hello everyone, I am looking to convert a snippet of JavaScript code into TypeScript. JavaScript function newState(name){ var state ={ name : name, age : 0 } return state } function initStates() { this.JamesStat ...

Reversing ngModel modifications does not accurately display changes in the view

Presently, my table contains editable cells, with the functionality to undo changes to each cell. To achieve this, I initially created a duplicate of each object in the array. Upon initialization, I mapped the array to create a new array with old values s ...

Testing the function that relies on a service through a unit test

I'm currently working on unit testing a component. However, I encountered an issue with one of its methods that utilizes a service and is causing a 'cannot read property 'then' of undefined' error. While I understand how to call a ...

Tips for creating a custom script in my React Native application

My React Native app requires a script to generate static files during the release process. The app is a game that utilizes pre-computed boards, which are resource-intensive to compute. Therefore, I am developing a script that will create these boards and s ...

Troubleshooting IONIC 4: Task failed to execute the dex archive transformation with external libraries merger for the debug version

I need help with my ionic 4 app development. I keep encountering an error whenever I try to build the android app. FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMerg ...

Personalizing the mat-checkbox

I'm trying to customize the checked icon in angular material mat-checkbox. Currently, it displays a white tick icon inside a colored background box, but I want to replace the tick with a cross when it is checked. After spending all day searching, I ha ...

Streamline copyright verification with Angular

We are currently working on an angular application that we plan to release as open-source. We make sure to include copyright information in every file, specifically in the .ts and .scss files. However, being human, there are times when we may forget to ad ...

Categorize items based on their defined attributes using Typescript

[origin object array and expect object array ][1] origin object array: 0: amount: 100000000000000000000 feeTier: 0.3 price: 00000 priceDecimal: 0000 status: "unknown" tokenXAddr: "0x*********" tokenXSymbol: "USDC" tokenYAddr: ...

Extending Vue components with TypeScript for enhanced styling features

Exploring Vuejs with TypeScript components has been an educational journey for me. While I found using class-based components quite intuitive, I've encountered errors when trying to use the Vue.extend({}) approach. Are there any resources such as arti ...

Transmitting a cookie across domains using an HTTP get request in Angular 2

Is there a way to send a cookie with Angular 2 across domains? const headers = new Headers({ 'Cookie': 'test=me'}); let options = new RequestOptions({ headers }); return this.http.get(this.specialUrl, options ) .map( (res: ...

When trying to open the phonegap-plugin-barcodescanner on Android Studio with Ionic 6 and Capacitor, I encounter an error

Encountered an issue while trying to build the app in Android Studio. The error message "Could not find method compile() for arguments [{name=barcodescanner-release-2.1.5, ext=aar}] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.Defau ...

Image uploading in Angular is not compatible with Internet Explorer, however, it functions correctly in Google Chrome

As of now, my implementation has been successful in all browsers except for Internet Explorer 11. Despite being able to successfully upload .jpeg, .jpg, and .png images in Google Chrome, I am facing issues when trying to upload them in IE 11. The code wo ...

Utilize Typescript to seamlessly transfer data between middleware stages

This is my first time creating an Express app using Typescript. I attempted to transfer data between middleware as I usually do in a JavaScript Express app In my JavaScript application, passing data was seamless What am I doing incorrectly here? Where h ...

Troubleshooting issue with getServerSideProps not functioning in Next.js while utilizing Next-redux-wrapper and TypeScript

When attempting to trigger an action as outlined in the documentation using the getServerSideProps function with the help of next-redux-wrapper store and redux-thunk, I am encountering the following TypeScript error: ts(2322): Type '({ req }: GetServe ...

Using Lerna with Docker for Next.js and GraphQL applications

Currently, I am working with lerna and everything runs smoothly locally. However, when I attempt to build the image and operate it through Docker, it does not function as expected. FROM node:16-alpine3.11 ENV NODE_ENV=production COPY . /app WORKDIR /app R ...

The error message "Property 'hideKeyboardAccessoryBar' does not exist on type 'Keyboard'." appeared while using the IONIC Moodle App

Having an issue in the IONIC Moodle App with a typescript error stating that property 'hideKeyboardAccessoryBar' does not exist on type 'Keyboard'. An ionic error occurred when running CMD, displaying the following error: [14:58:02] ...