0

I have a hybrid application in AngularJS (1.5.6) and Angular (7.2.0) in which I am trying to implement routing which works for both Angular and AngularJS components. I have used the following link to change the routing configuration for Angular components : https://github.com/angular/angular.io/tree/master/public/docs/_examples/upgrade-phonecat-3-router/ts/app

Problem: When i try to navigate from an Angular component to another Angular component with router.navigate method, it works fine. However, if I try to do some other navigation to any other page or back to the same page using the same router.navigate method, nothing happens, there is no change in the url as well.

However, if I refresh the page (on the second page which is already navigated) then any navigation from that page takes place as if the router is initialized as the first navigation.

In short, router.navigate method works only for the first time. For the subsequent navigation it fails unless the page is refreshed.

/* app.module.ajs.ts  (AngularJS module) */

'use strict';

import routeProviderConfig from './config';
import cdcAppComponent from './cdc.app';

import CDC_CONSTANTS from './constants';
import CDC_SERVICES from './service';
import CDC_CONTROLLERS from './controller';
import CDC_DIRECTIVES from './directives';
import CDC_FILTERS from './filter';
import { environment } from '../environments/environment';

declare var angular: angular.IAngularStatic;

const MODULE_NAME = 'app';

angular.module(MODULE_NAME, [
   'ui.bootstrap',
   'ngRoute', 'ngResource', 'ngCookies', 'ngMessages', 'ngMask', 'ngSanitize',
   'pascalprecht.translate',
   'ui.grid', 'ui.grid.resizeColumns', 'ui.grid.selection', 'ui.grid.pinning', 'ui.grid.pagination', 'ui.grid.resizeColumns',
   'ui.grid.autoResize', 'ui.grid.edit', 'ui.grid.cellNav', 'ui.grid.selection', 'ui.grid.expandable', 'ui.grid.exporter',
   'ui.select',
   'toaster',
   'smart-table',
   'xeditable',
   'ngDialog',
   'BotDetectCaptcha',
   CDC_CONSTANTS, CDC_CONTROLLERS, CDC_SERVICES, CDC_FILTERS, CDC_DIRECTIVES
]).config(routeProviderConfig)
   .component('cdcApp', cdcAppComponent)
   .config(['$httpProvider', function ($httpProvider: angular.IHttpProvider) {
      $httpProvider.interceptors.push('TokenAuthInterceptor')
   }])
   .config(['captchaSettingsProvider', function (captchaSettingsProvider) {
      captchaSettingsProvider.setSettings({
         captchaEndpoint: environment.apiUrl + 'cdcapi/botdetectcaptcha'
         //For Cloud
        //captchaEndpoint: 'cdc/botdetectcaptcha'
      });
   }]);


export default MODULE_NAME;


/* app.module.ts */

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS, HttpClient } from '@angular/common/http';

import { UpgradeModule } from '@angular/upgrade/static';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import moduleName from './app.module.ajs';


   /* all entries not shown*/

import { AppRoutingModule } from './app-routing.module';
import { routeParamsProvider } from './ajs-upgraded-providers';

declare var angular: angular.IAngularStatic;

const MODULE_NAME = 'app';


@NgModule({
  declarations: [
       /* all entries not shown*/
  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  imports: [
      /* all entries not shown*/
    AppRoutingModule,
   /* all entries not shown*/
  ],

  providers: [
   /* all entries not shown*/
    routeParamsProvider,
   /* all entries not shown*/
  ],
  entryComponents: [   
   /* all entries not shown*/
  ],

  //bootstrap: [AppComponent]
  exports: [NgxSpinnerModule],
})
export class AppModule {
  constructor(private upgrade: UpgradeModule) { }
  ngDoBootstrap() {

      /* all entries not shown*/

    console.log('Going to Bootstrap from app module');
    this.upgrade.bootstrap(document.documentElement, [moduleName], { strictDi: true });

  }

}

/* ajs-upgraded-providers.ts */

export abstract class RouteParams {
  [key: string]: string;
}

export function routeParamsFactory(i: any) {
  return i.get('$routeParams');
}

export const routeParamsProvider = {
  provide: RouteParams,
  useFactory: routeParamsFactory,
  deps: ['$injector']
};



/* app-routing-module.ts */

import { NgModule } from '@angular/core';
import { Routes, RouterModule, UrlHandlingStrategy, UrlTree, ExtraOptions } from '@angular/router';
import { APP_BASE_HREF, HashLocationStrategy, LocationStrategy } from '@angular/common';

import { LabReferralComponent } from './lab/labRefInst';
import { WorkListComponent } from './lab/workList.1';
import { NurseComponent } from './nurse/nurse.1';

export class Ng1Ng2UrlHandlingStrategy implements UrlHandlingStrategy {
    shouldProcessUrl(url: UrlTree) {
        return url.toString() === '/' || url.toString() === '/login';
    }
    extract(url: UrlTree) { return url; }
    merge(url: UrlTree, whole: UrlTree) { return url; }
}

const routes: Routes = [
    { path: 'labreferral', component: LabReferralComponent },
    { path: 'workList', component: WorkListComponent },
    { path: 'samplecollection', component: NurseComponent }, 
];

const config: ExtraOptions = {
    anchorScrolling: 'enabled',
    onSameUrlNavigation: 'reload',
    scrollPositionRestoration: 'enabled',
    useHash: true, 
    initialNavigation: false
};

@NgModule({
    imports: [RouterModule.forRoot(routes, config),],

    exports: [RouterModule],
    providers: [
        { provide: LocationStrategy, useClass: HashLocationStrategy },
        { provide: UrlHandlingStrategy, useClass: Ng1Ng2UrlHandlingStrategy }
    ]
})
export class AppRoutingModule { }


/* config.ts  (angularJS route config*/  

'use strict';

routeProviderConfig.$inject = ['$routeProvider', '$translateProvider'];

function routeProviderConfig($routeProvider, $translateProvider) {
    $routeProvider.
        when('/', {
            template: '<login></login>'
        }).
        when('/home', {
            template: '<dashboard></dashboard>'
        }).
        when('/report', {
            template: '<report></report>'
        }).      
        otherwise({
            redirectTo: '/'
        });

    $translateProvider
        .useStaticFilesLoader({
            //prefix: './assets/translations/locale-',
            prefix: './assets/translations/',
            //prefix: './assets/i18n/',
            suffix: '.json'
        })
        .preferredLanguage('en')
        .useLocalStorage()
        .useMissingTranslationHandlerLog()
        .useSanitizeValueStrategy('escape');

}

export default routeProviderConfig;

/*
    .config(function ($httpProvider) {
    $httpProvider.interceptors.push('TokenAuthInterceptor');

}).config(function (captchaSettingsProvider) {
    captchaSettingsProvider.setSettings({
        captchaEndpoint: '/cdc/botdetectcaptcha'
    });
});*/

/** Calling router.navigate from first angular component to second angular component **/

let url: any = '/samplecollection';
let link = [url];
this._router.navigate(link, { queryParams: { selectedOrder: JSON.stringify(selectedOrder), navFrom: navFrom } });

This navigation happen and the second page (component) is displayed.

/But when try to navigate back to the first page using:/

this._router.navigate(['/workList'], { queryParams: { view: 'workList' } });

/* navigation is not happening, the url remains the same, but I refresh the page (present url of second page) and then try to navigate, it works

Can anyone please explain this behaviour? Is it possible to use both Angular and AngularJS routing in a hybrid environment? Can anyone suggest a better solution, if the above approach will not work?

Lucas
  • 9,871
  • 5
  • 42
  • 52
Riyaz K
  • 1
  • 1

1 Answers1

1

Try adding setUpLocationSync(this.upgrade) when doing bootstrap like this:

ngDoBootstrap() {

      /* all entries not shown*/

    console.log('Going to Bootstrap from app module');
    this.upgrade.bootstrap(document.documentElement, [moduleName], { strictDi: true });
setUpLocationSync(this.upgrade);
}

If you are using hash based routing then pls try: setUpLocationSync(this.upgrade,"hash")

blackgreen
  • 34,072
  • 23
  • 111
  • 129