After performing the `ng build --prod` command in Angular 4, deep linking functionality may not

I have a requirement to display different screens in my Angular application based on the URL pasted by the user in the browser:

  1. http://localhost/screen1 (should show screen1)
  2. http://localhost/screen2 (should show screen2)

To achieve this, I have set up two components - Screen1Component and Screen2Component for the respective paths.

In `screen1.component.ts`:

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

@Component({
selector: 'app-screen1',
templateUrl: './screen1.component.html',
styleUrls: ['./screen1.component.css']
})
export class Screen1Component implements OnInit {
    constructor() {
    }

    ngOnInit() {
    }
}

In `screen2.component.ts`:

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

@Component({
    selector: 'app-screen2',
    templateUrl: './screen2.component.html',
    styleUrls: ['./screen2.component.css']
})
export class Screen2Component implements OnInit {
    constructor() {
    }

    ngOnInit() {
    }
}

To make these modules children of the base route, I defined them as follows in `routing.module.ts`:

import {ModuleWithProviders} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {Screen1Component} from './screen1/screen1.component';
import {Screen2Component} from './screen2/screen2.component';

const appRoutes: Routes = [
    {
        path: '',
        children: [
            {
                path: 'screen1',
                component: Screen1Component
            },
            {
                path: 'screen2',
                component: Screen2Component
            }
        ]
    }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

Additionally, here's how I configured my main.ts:

import {ModuleWithProviders} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {Screen1Component} from './screen1/screen1.component';
import {Screen2Component} from './screen2/screen2.component';

const appRoutes: Routes = [
    {
        path: '',
        children: [
            {
                path: 'screen1',
                component: Screen1Component
            },
            {
                path: 'screen2',
                component: Screen2Component
            }
        ]
    }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

Furthermore, my `app.component.ts` looks like this:

import {Component} from '@angular/core';
import {Screen1Component} from './screen1/screen1.component';
import {Screen2Component} from './screen2/screen2.component';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'app works!';
}

As for `app.module.ts`:

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

import {AppComponent} from './app.component';
import {Screen1Component} from './screen1/screen1.component';
import {Screen2Component} from './screen2/screen2.component';
import {routing} from './routing.module';

@NgModule({
    declarations: [AppComponent, Screen1Component, Screen2Component],
    imports: [BrowserModule, routing],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {
}

The content of `app.component.html` is:

<h1>{{title}}</h1>
<router-outlet></router-outlet>

For `index.html`:

<!doctype html>
<html lang="en>
    <head>
        <meta charset="utf-8">
        <title>Tryout</title>
        <base href="/">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="icon" type="image/x-icon" href="favicon.ico">
    </head>
    <body>
        <app-root>Loading...</app-root>
    </body>
</html>

While I am able to successfully deep link to the components when running `npm start` with `ng serve -o`, after creating a production build using `ng build --prod`, directly accessing URLs like http://localhost/ loads the application but hitting http://localhost/screen1 or http://localhost/screen2 results in a 404 error.

I have tried deploying the generated files to an Nginx server with no success. Any assistance on resolving this issue would be highly appreciated.

Answer №1

Ensure that your route path is not empty before adding children to it.

If you want to use routes without children, follow the example below:

const appRoutes: Routes = [
    {path: 'page1', component: Page1Component},
    {path: 'page2', component: Page2Component}},
    {path: '', redirectTo:'/page1', pathMatch:'full'}
];

Remember that Angular will choose the first matching route according to the configuration.

The issue was related to server routing strategies. The application functioned correctly in lite-server but encountered problems with other servers.

Answer №2

The script is functioning properly and will operate smoothly when using ng serve or lite-server. To ensure compatibility with my Nginx server, I followed the configuration guidelines outlined in this resource - https://angular.io/guide/deployment#production-servers

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

A perplexing issue arises in Angular 8 where a component placed between the header and footer fails to display, despite no errors being

I've encountered an issue with angular routing that I need assistance with. In the app.component.html file, we have: <router-outlet></router-outlet> The configuration in the app-routing.module.ts looks like this: import { NgModule } fr ...

What steps can be taken to implement jQuery within an Angular 15 npm package?

In my development process, I often create my own npm packages using Angular and Typescript. One of the packages I am currently working on is a PDF viewer service, which includes a file named pdf-viewer.service.ts with the following code: import { Behavior ...

Recording the details of an Angular project through the utilization of Compodoc

I am currently in the process of documenting my Angular + Typescript application using Compodoc. To install Compodoc, I utilized npm and executed the following command: 'npm install -g compodoc'. And included "compodoc": "./node_modules/ ...

Tips for updating Angular HTML with data received from Socket.IO

I am currently working on a socket program that is listening and providing log data. The socket is sending the correct data as I can see it in the console. Below is a snippet of my code: export class RoboLogComponent implements OnInit { dataToShow:any @V ...

Who is in charge of initializing "background" services within Angular?

I have been studying the Angular service workers documentation (https://angular.io/guide/service-worker-communications). The examples provided demonstrate services used for managing service worker lifecycle handlers such as update and failed lifecycle. My ...

Tests in Angular2 are executed before the variables in compileComponents are initialized

I'm encountering an issue with an Angular2 text component where I receive the following error message when trying to run the testrunner: Component: Product Component Should ensure component subscribes to service EventEmitter on instantiation Failed: ...

Passing an array of items as a property to a child component in React with Typescript is not possible

In my project, I have multiple classes designed with create-react-app. I am trying to send an array of objects to child components as illustrated below. Items.tsx import * as React from 'react'; import ItemTable from './ItemTable'; imp ...

Discover the Hassle-Free Approach to Triggering Angular Material Menu with ViewChild and MatMenuTrigger

Is there a way to programmatically open an Angular Material menu using a Template Reference Variable on a button trigger that is accessed in the component through ViewChild? I want the menu to open when the mouse hovers over it, instead of just clicking i ...

Angular 4: Loading components sequentially

I am currently working with Ionic 3 and based on the Angular 4 framework. I have a question regarding loading multiple children components asynchronously, one by one: Load parent component; Load first child component; After the first child component is l ...

Extending parent context in dependencies through OOP/Typescript as an alternative to using "extends"

Introducing a custom class called EventBus has been a game-changer for me. This class allows for easy attachment of on/off/once methods to any class that extends it, enabling the creation of an array of events that can be listened to. Currently, I find my ...

Pass the identical event to multiple functions in Angular 2

On my homepage, there is a search form with an input box and select dropdown for users to search for other users by location or using html5 geolocation. When a user visits the page for the first time, they are prompted to allow the app to access their loca ...

State array is being updated

In my main container, I am setting a context for its children : import React, {useRef, useEffect, useState, ReactNode, createContext, useContext} from 'react'; import Provider from "./Provider"; import Consumer from "./Consumer&quo ...

What is the source of the compiler options in tsconfig.json?

Currently utilizing Typescript in NestJs, I have incorporated various packages. However, the specific package responsible for altering these settings remains unknown to me: "checkJs": false, "skipLibCheck": true Is there a method to ...

Do not generate authentication code in JHipster using the --skip-server flag

Is there a reason why the authentication part is lost when generating a project with '--skip-server'? yo jhipster --skip-server It seems that upon generating the project without the server, the authentication gets affected (on AJS/A2). Is thi ...

Adjust the control's value as you monitor any modifications

As I monitor the changes within a reactive form by subscribing to the value changes, I have encountered an issue where certain values unset in the form prevent the Angular Material Slide Toggle from toggling to false. This is crucial as it affects the "Act ...

I'm running into issues transferring data between Angular and an API

While working on an Angular project, I encountered an issue where I couldn't populate data from an API into a table. I suspected there was an error in the datasource section but couldn't pinpoint it. When checking the console, I verified that the ...

Secure Socket Layer (SSL) Certificate Functions Properly for Domain, However Not for

I have successfully configured my domain sub.example.com on an Ubuntu server and secured it with HTTPS using Certbot. However, I am facing an issue with accessing APIs that are set up to be accessed on a specific port (2500) of the domain. When I visit exa ...

Is it possible for the Chrome debugger to locate TypeScript files that have not been served by the

I am creating .js.map files to assist in debugging my TypeScript code within Chrome. The js.map files specify the correct location of the TypeScript in the "sources" property. sourceRoot is set to "", and sources represent the path to the TypeScript code ...

A guide on how to identify the return type of a callback function in TypeScript

Looking at this function I've created function computedLastOf<T>(cb: () => T[]) : Readonly<Ref<T | undefined>> { return computed(() => { const collection = cb(); return collection[collection.length - 1]; }); } Thi ...

An issue occurred: Unable to access the 'login' property because of a TypeError

Setting up a login page and declaring an object in my login.ts file. public User: { login:"", senha:"", }; Utilizing [ngModel] to save values within the parameters of the object. <ion-item> <ion-label floating>Enter ...