Having trouble with Angular routing in a .NET MVC 5 application with Angular 6?

I have integrated an Angular 6 application into an existing .NET MVC 5 application. A fallback route was set up in the MVC app (RouteConfig.cs) to direct "unknown" routes to the Angular app's router module (app.routes.ts). However, it seems that the routes defined in the Angular app are not working as expected, and the associated components are not loading.

The development environment includes Visual Studio 2017 Enterprise 15.6.7, a standard .NET Web application for MVC 5.2.3.0 (not .NET Core), Node.js 8.11.3, npm 6.3.0, Typescript 2.9.2, Angular CLI 6.0.8, Angular 6.0.3, bootstrap 3.3.7, jquery 3.3.1, and runs on Windows 10 x64 OS.

Below is the RouteConfig.cs file for the MVC app with the catch-all route at the bottom:

 [c# code will be here] 

Upon creating the Angular app using CLI, the package.json entry for Typescript defaults to version 2.7.2. The dependencies listed include various Angular modules along with other necessary libraries.

The app.routes.ts file defines simple routing for the application. It includes paths for displaying EventsListComponent and EventDetailsComponent.

 [typescript code will be here] 

In the EventsAppModule, AppRoutingModule is imported to enable routing functionality. However, when trying to use routing in the main component/page of the app, EventsListComponent does not load properly. Alternatively, using a different tag allows EventsListComponent to display correctly.

Furthermore, accessing specific routes like http://localhost:39420/events or http://localhost:39420/events/1 results in blank pages being rendered instead of the expected content.

Answer №1

redirectTo requires the precise path for the router to navigate to, including a leading / before the specified route path.

To ensure that the EventsListComponent component loads correctly, update redirectTo: 'events' to redirectTo: '/events' in your route configuration.

Additionally, include pathMatch: 'full' in this route definition:

{
    path: '',
    redirectTo: '/events',
    pathMatch: 'full'
}

For further assistance, you can refer to this StackBlitz project.

Answer №2

If there are no other routes that match the request, you need to catch all so Angular can handle it properly.

// This is a catch-all for when no other routes match the request; let Angular 2 router handle it...
            routes.MapRoute(
                name: "default",
                url: "{*url}",
                defaults: new { controller = "Home", action = "Index" } // The view that initializes Angular 2 app
            );

Make sure to remove the defaults as follows and avoid creating a Controller/View for Angular.

// This is a catch-all for when no other routes match the request; let Angular 2 router take care of it...
            routes.MapRoute(
                name: "default",
                url: "{*url}",// no view needed
            );

After executing the command:

ng build --prod

Copy the dist files into a directory such as 'myangularapp' within the root directory of your MVC application. Remember to update the base tag href attribute by running:

ng build --prod --base-href=/myangularapp/.

Next, create a web.config file in the directory containing your Angular files ('myangularapp'). See sample below.

<?xml version="1.0"?>
<configuration>
  <system.web></system.web>
  <system.webServer>
    <rewrite>
      <rules>
        <!--Redirect certain traffic to index page-->
        <rule name="Index Rule" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          </conditions>
          <action type="Rewrite" url="index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

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

Auto-login functionality in Ionic 2 is failing to work properly on Android Nougat within the Ionic development application

I've been working on an Ionic application and have successfully implemented the login and registration functionalities using JWT. The app checks for authentication by validating the token, and if the token is missing or different from the server, the ...

NextJS function utilizes its own references within React and automatically fetches data without the need for an import

I recently purchased this template and I'm trying to figure out which page the code snippet "{getLayout(<Component {...pageProps} />)}" is directed to during the initial load. It seems like it might be a global variable hidden somewher ...

Guide to adding jquery with typings installation

Need assistance: typings install jquery --global typings ERR! message Unable to find "jquery" ("npm") in the registry. Did you want to try searching another source? Also, if you want contribute these typings, please help us: https://github.com/typings/re ...

Encountered issues while trying to utilize wasm function within Vue framework

When attempting to integrate wasm with Vue, I encountered a frustrating issue where the startQuorum function in my wasm file could not be located. import { Go } from './wasm_exec' import quorumWasmUrl from './lib.wasm' export const sta ...

Understanding the significance of the add() operator in RxJS

Can someone clarify the purpose of the add() operator in rxjs? I've seen it mentioned that it includes a teardown function, but there isn't much detail on what exactly a teardown is or why it's necessary. My specific query relates to impleme ...

What causes functions operating on mapped objects with computed keys to not correctly infer types?

If you are seeking a way to convert the keys of one object, represented as string literals, into slightly modified keys for another expected object in Typescript using template string literals, then I can help. In my version 4.9.5 implementation, I also ma ...

Typescript Error: Issue encountered while passing props. Unable to access properties as they are undefined

I encountered an issue where I created an object of a certain type and attempted to pass it to a component. However, when passing the props, I received an error message stating that it cannot read properties of undefined ('stepOne'). The error sp ...

Update the data in Firebase, but revert it back to the original state after a few seconds with the use of "angularFire."

I'm currently working on updating data in the Firebase Realtime Database using Angular and AngularFire. The issue I'm facing is that even though the data changes successfully, it reverts back to the original data after a few seconds. Below is the ...

How to Delete Multiple Rows from an Angular 4 Table

I have successfully figured out how to remove a single row from a table using splice method. Now, I am looking to extend this functionality to remove multiple rows at once. html <tr *ngFor="let member of members; let i = index;"> <td> ...

Sorting through a JavaScript array

I am facing a peculiar problem while trying to filter an array in TypeScript. Here is the structure of my object: Sigma.model.ts export class Sigma { sigmaId: number; name: string; userId: number; starId: string; } `` The starId property contains com ...

Handling a JSON payload within an ASP.NET MVC controller

When using jQuery post to send a json-object to my asp.net server, I am receiving a string that looks like this: "'{\"refNr\":\"124460\",\"dokid\":1}'" I am struggling to find a method that can extract the data in ...

Encountering NullInjectorError during Angular 5 Upgrade: InjectionToken LocaleId Provider Not Found

Recently, I made the transition from Angular 4 to Angular 5 using CLI 1.5.4 for my app. Along with that, I have a shared library set up via npm link. To successfully build my project after the upgrade, I had to make changes in my tsconfig.app.json file as ...

Guide to Rolling a Set of 5 Dice

I am looking to develop a game involving 5 dice. I have already created a function to roll one die using a random method, but I am unsure how to extend this functionality to the remaining four dice without having to create a separate method for each one. ...

Saving a group of selected checkboxes as an array in Ionic: a step-by-step guide

I am working on a simple form with checkboxes and I need to send only the checked boxes to TypeScript. However, when I attempt to save the data by clicking the save button, I encounter an error message {test: undefined} Below is the form layout: <ion-c ...

Manipulate MySQL data in Node.js by storing it in a variable

Struggling to grasp the concepts of nodeJS/typescript and how to effectively save database query results into variables for return. Seeking assistance to solve the problem faced: Here is a method snippet that needs help: public getAllProducts(): ProductA ...

Possibility for Automatic Type Inference in Generics

Is there a way to have a method infer the type of function parameter without specifying its generic? Currently it is 'GET' | 'POST', but I only need the literal 'GET' const func = <Params, Method extends "GET" | & ...

I'm having trouble setting a value for an object with a generic type

I am attempting to set a value for the property of an object with generic typing passed into a function. The structure of the object is not known beforehand, and the function receives the property name dynamically as a string argument. TypeScript is genera ...

The functionality of the Angular directive ngIf is not meeting the desired outcome

We are currently working on transferring data from one component to another using the approach outlined below. We want to display an error message when there is no data available. <div *ngIf="showGlobalError"> <h6>The reporting project d ...

Potential keys + keys that are present in the `initialData`

Is there a way to specify the type of data in order to include all keys that exist in initialData plus additional keys from Item as Partial(optional)? class TrackedInstance<Item extends Record<string, any>, InitialData extends Partial<Item> ...

Incorporating a new function into a TypeScript (JavaScript) class method

Is it possible to add a method to a method within a class? class MyClass { public foo(text: string): string { return text + ' FOO!' } // Looking for a way to dynamically add the method `bar` to `foo`. } const obj = new MyCl ...