Implement Angular routing in an AngularJS/Angular hybrid application to enable seamless page reloads

I am working on implementing Angular routing in my hybrid AngularJS/Angular application. I have created an app-routing.module.ts file with the following configuration:

import { ModuleWithProviders } from "@angular/core";
import { Routes, RouterModule, ExtraOptions } from '@angular/router';
import {SignInComponent} from "./modules/login/components/sign-in/sign-in.component";
import {ActivationComponent} from "./modules/login/components/activation/activation.component";

const routes: Routes = [
  {
    path: 'sign-in',
    component: SignInComponent
  },
  {
    path: 'activation',
    component: ActivationComponent
  },
  {
    path: '',
    pathMatch: 'full',
    redirectTo: '/activation'
  },
  {
    path: '**',
    pathMatch: 'full',
    redirectTo: '/activation'
  }
];

export const routingModule: ModuleWithProviders = RouterModule.forRoot(routes);

In my app.module.ts file, I added the routingModule to the "imports" array and in app.component.html, I included the following buttons:

<button (click)="goto('sign-in')">go to sign in</button>
<button (click)="goto('activation')">go to activation</button>

<router-outlet></router-outlet>

The Angular routing works perfectly when using just Angular without any issues.

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8>
  <title>Angular</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></app-root>
</body>

</html>

However, when I add my AngularJS code by including

this.upgrade.bootstrap(document.body, ['app']);

the Angular routing no longer just refreshes the content of the "router-outlet" tag, but reloads the entire page instead. Removing the above line resolves the issue.

Has anyone encountered a similar problem and can suggest a solution for making Angular routing function correctly within a hybrid AngularJS/Angular application? Thank you.

Answer №1

It seems that the configuration of AngularJS and Angular Router is not set up correctly. To resolve this issue, please follow the steps outlined below:

  1. Remove the default route (.otherwise) from the AngularJS routing configuration.
  2. In the Angular router settings, implement the UrlHandlingStrategy interface to handle routing for specific URLs and prevent conflicts between Angular and AngularJS routers-
export class Ng1Ng2UrlHandlingStrategy implements UrlHandlingStrategy {

  shouldProcessUrl(url: UrlTree): boolean {
    return url.toString().startsWith('/ng/');
  }

  extract(url: UrlTree): UrlTree { return url; }
  merge(newUrlPart: UrlTree, rawUrl: UrlTree): UrlTree { return newUrlPart; }
}
  1. Add the above class (Ng1Ng2UrlHandlingStrategy) as a provider in the root module for handling URL strategy-
providers: [
  { provide: UrlHandlingStrategy, useClass: Ng1Ng2UrlHandlingStrategy }
]
  1. Include both AngularJS and Angular outlets/directives in the app component HTML file.
<router-outlet></router-outlet>
<div class="ng-view"></div>
  1. To enable support for HTML5-based routing in a hybrid app, use hash based routing along with the function setUpLocationSync(upgrade) in the main.ts file as shown below-
upgrade.bootstrap(document.body, ['app']);
setUpLocationSync(upgrade);

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

Troubleshooting issue: aria-expanded not functioning properly in a Next.js application

Summary: In a standard index file using Tailwind CSS, a button functions properly. However, when attempting to implement it in a Next.js project with TypeScript files, issues arise with the @click and aria-expanded attributes. Challenge: The specific prob ...

How can you transfer data from a parent component to a child component using input?

To display the chart in any component using @Input, you must transfer data from the parent component, which contains all the chart logic, to the child component. The parent component, logs.component, and the child component, echarts.component, need to com ...

What steps do I need to take to integrate an Instagram Reel onto my website using the embed code?

I am currently facing an issue with embedding reels on my website. Even though I can view the reel, I am unable to playback the video. When embedding a video or carousel on my website, I have no trouble viewing it. However, when it comes to reels, all I se ...

How can I access a file uploaded using dxFileUploader?

I am facing an issue with retrieving a file from dxFileUploader (DevExpress) and not being able to read it in the code behind. The file is only appearing as an object. Here is My FileUploader : { location: "before", ...

Capturing a center mouse click event in a directive for Angular 6

I created a unique custom directive where I aim to capture middle mouse button click events. Initially, I thought it would be a straightforward process by setting the normal click event and working from there. However, I noticed that it only triggers when ...

Presenting validated material using Angular.js

app.controller('PageCtrl', ['$scope', '$stateParams', '$state', 'USER_ROLES', 'AuthService', function($scope, $stateParams, $state, USER_ROLES, AuthService){ //console.log("Page Controller repor ...

Nuxt SSR encounters issues when modifying data variables

There is an issue with my Nuxt app where sometimes when the page loads, I encounter an error in the console that causes the page to stop loading other components. The error message reads: Cannot read properties of undefined (reading 'resolved') ...

Using T and null for useRef in React is now supported through method overloading

The React type definition for useRef includes function overloading for both T|null and T: function useRef<T>(initialValue: T): MutableRefObject<T>; // convenience overload for refs given as a ref prop as they typically start with a null ...

Navigating the parent navController in Ionic 2: A step-by-step guide

I'm currently honing my skills in Ionic 2 by creating a basic app, but I've encountered an issue that has me stumped. The app features an ion-nav element for the login page, then transitions to a tabs navigator after successful login. The struct ...

Why is the quantity of my item being increased? My method is adding it when it shouldn't be

I have a project in Angular that involves an online store. However, every time I click the button "agregar a carrito" (add to cart in Spanish), my item's quantity seems to increase inexplicably. ts. removeItem(item: iProduct) { if (item.quantity ...

Using the jasmine framework to create conditional test cases

Currently, I am working on Jasmine and my goal is to ensure that the test cases run only when the site's response status is okay (200). If the site fails to load, I do not want the test cases to execute. To achieve this, I am checking the site's ...

Implementing Injector Class instead of ReflectiveInjector class is a great way to improve performance

I have been experimenting with dynamic loading data in angular. To achieve this, I initially used the following code snippet - const inputProviders = Object.keys(data.inputs).map(inputName => { return { provide: inputName, useValue: data.inputs[inp ...

What are the steps to manipulate third party API data with the Node.js 'Request' module, prior to transmitting it to the frontend?

Being a newcomer to NodeJs, I took to Google for assistance but came up empty. My challenge lies in editing the json data retrieved from an API link and sending it to frontend AngularJS as is. app.get('/getCustomers', bodyParser.urlencoded({exte ...

The React application, when built using `npm run build`, experiences difficulty loading image sources after deployment to App Engine

In my React frontend application, I have the logo.png file being loaded in Header.tsx as an img element like this: <img className={classes.headerLogo} src={'logo.png'} alt={"MY_LOGO"}/> The directory structure looks lik ...

Cross-Origin Request Blocked in Browser (Angular Front-end, Quarkus Back-end)

application.properties #WEB quarkus.tls.trust-all=true quarkus.http.cors=true Controller @POST @Path("/result") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(summary = "Display Ev ...

Encountering an issue with Angular when trying to add the urlRouterProvider

When I include the parameter ".config(function($urlRouterProvider)" in my config function, I encounter the following error: Uncaught object angular.min.js:6 (anonymous function) angular.min.js:6 (anonymous function) angular.min.js:34 q angular.min.js:7 f ...

Using the Google Maps API with AngularJS, you can easily retrieve a list of cities located between two markers on the map

Is it possible to display a list of major cities as via points when the user selects starting and end locations? I am utilizing AngularJS and the Google Maps API. Any guidance on this functionality would be appreciated. ...

Angular watch triggering even when the old and new values remain unchanged

function displayController($scope) { $scope.currentView = myCustomInstance.currentView; $scope.$watch($scope.currentView, function(newValue, oldValue) { console.log(newValue); cons ...

Looking to adjust the header height of an angular mat-table with column groups? The table I'm currently working on has both main headers and sub headers

I recently utilized some code snippets from this StackBlitz example. However, I am facing an issue with the height property not functioning as expected. Is there a method to customize the height of both the main header and subheader? th.mat-header-cell, ...

Showing information from a JSON file in a layout

Hey there! I could really use some assistance in displaying my data. So, I've got this custom provider that calls my API, and everything is running smoothly. Currently, I'm focusing on the page titled 'playing', and here's a glim ...