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

Discover the latest Angular edition through coding

Is there a simple way to display my Angular version on a website using code instead of checking it in the command line with 'ng --version'? ...

Ag-Grid is displaying a third column that is not present in my dataset

Recently, I've been working with Angular and incorporating the Ag-Grid into my project. My goal is to display a grid with two columns; however, upon implementation, an unexpected third separator appears as if there are three columns in total. Even w ...

What is the process for developing a custom pipe in Angular 12 with ngx-translate and internationalization support?

I've been working on internationalization for my angular project, which is an admin portal using @ngx-translate. Unfortunately, I've hit a roadblock and need to start over with the internationalization task. Any suggestions on how to approach thi ...

Vue: Simple ways to retrieve state data in MutationAction

I'm having trouble accessing the state inside @MutationAction Here is the setup I am using: Nuxt.js v2.13.3 "vuex-module-decorators": "^0.17.0" import { Module, VuexModule, MutationAction } from 'vuex-module-decorators' ...

When passing an object to a function inside a promise.then, Typescript may generate an error indicating that the object could

Snippet of code below is extracted from a request controller function. Goal The aim was to generate various notifications based on the paths that are modified. let farmerToUpdate = await FarmerModel.findById(farmerId) if (!farmerToUpdate) throw new cont ...

How do React Native proxies differ from vanilla React proxies in their functionality?

Trying to retrieve data from an API running locally on port 5000 of my device, I recalled setting the proxy in package.json when working on React web applications: "proxy": "https://localhost:5000" Attempting to fetch information f ...

Question from Student: Can a single function be created to manage all text fields, regardless of the number of fields present?

In my SPFX project using React, TypeScript, and Office UI Fabric, I've noticed that I'm creating separate functions for each text field in a form. Is there a way to create a single function that can handle multiple similar fields, but still maint ...

Obtain a 404 error status code when the route cannot be found in Angular 6+ using Universal

After launching my project with Universal, I set up my .htaccess file to direct all requests to the index.html, which serves as the root page for my Angular application. I followed the instructions on https://angular.io/guide/universal to enable sharing l ...

react-i18next: issues with translating strings

I encountered a frustrating issue with the react-i18next library. Despite my efforts, I was unable to successfully translate the strings in my application. The relevant code looked like this: App.tsx: import i18n from 'i18next'; import { initR ...

Navigating through segment tabs on Ionic 3 with a simple swipe

In the code snippet provided, segments from Ionic 3 are used with ngSwitch and ngModel. However, I am looking for a way to switch between segment tabs by simply swiping on the content area, rather than tapping the tabs at the top. Is there a way to achieve ...

Unable to locate the namespace for the installed library

Looking for a solution in my ExpressJS setup with Pino logger. I am trying to create a class that can be initialized with a Pino logger. Here is the code snippet: import express, { NextFunction, Request, Response } from 'express'; import pino fr ...

Navigating the use of property annotations in Mapped Types with remapped keys

After exploring the concept of Key Remapping in TypeScript, as shown in this guide, I am wondering if there is a way to automatically inherit property annotations from the original Type? type Prefix<Type, str extends string> = { [Property in keyo ...

Transferring data seamlessly from EF .NET Core 6 to Angular

I am facing an issue while trying to fetch data from my ASP.NET Core 6 backend to Angular: Error: NG0900: Error trying to diff '[object Object]'. Only arrays and iterables are allowed export class EmployeesListComponent { em ...

Updating displayed content based on orientation switch

Two components, A and B, are displayed simultaneously - A on the left and B on the right - when the device is in landscape mode. In portrait mode, either A or B will be displayed based on user selection. The components can transition from A to B and vice v ...

What is the best way to determine the number of queryClient instances that have been created?

Currently, I am managing a large project where the code utilizes useQueryClient in some sections to access the queryClient and in other sections, it uses new QueryClient(). This approach is necessary due to limitations such as being unable to invoke a Reac ...

How can I utilize the color prop in the theme file to style new variants more comprehensively with MUI theming?

I am working on creating a custom variant for an MUI button where the color specified in the color prop should be applied as both the border and text color. While the MUI documentation offers a suggested approach, it requires addressing each available col ...

Navigating the terrain of multiple checkboxes in React and gathering all the checked boxes

I am currently developing a filter component that allows for the selection of multiple checkboxes. My goal is to toggle the state of the checkboxes, store the checked ones in an array, and remove any unchecked checkboxes from the array. Despite my attemp ...

Failure to invoke Jest Spy

Currently, I am attempting to conduct a test utilizing the logging package called winston. My objective is to monitor the createlogger function and verify that it is being invoked with the correct argument. Logger.test.ts import { describe, expect, it, je ...

Guide to creating numerous separate subscriptions in angular 6

Can you explain the differences between flatMap(), switchmap(), and pipe()? Which one would be most suitable for the given scenario? I need to call the next method once both responses are received. this.jobService.getEditableText('admins', compar ...

Tips for handling Firebase JS SDK errors within try-catch blocks

Attempting to type the err object in a function that saves documents to Firestore has been challenging. async function saveToFirestore(obj: SOME_OBJECT, collection: string, docId: string) { try { await firebase.firestore().collection(collection).doc( ...