ui-router/angular-hybrid - route not recognized on initial load/reload - angularjs

It seems that routes that are registered within ng2+ module using the #ui-router/angular-hybrid are not recognized on initial load/reload. The same route is working if e.g. navigated by typing the url.
I've followed the official upgrade docs from #ui-router/angular-hybrid
Here is the ng2+ AppModule code:
const states: NgHybridStateDeclaration[] = [
{
name: 'x',
url: '/x',
component: XComponent
}
];
enableProdMode();
#NgModule({
imports: [
BrowserModule,
UpgradeModule,
UIRouterUpgradeModule.forRoot({states: states}),
ComponentsModule,
DirectivesModule
],
declarations: [AppComponent],
exports: [],
entryComponents: [],
providers: [],
bootstrap: []
})
export class Ng2AppModule {
constructor(
#Inject(forwardRef(() => UpgradeModule)) private upgrade: UpgradeModule,
#Inject(forwardRef(() => Config)) private config: Config
) {}
ngDoBootstrap() {
this.upgrade.bootstrap(document as any, ['app'], { strictDi: true });
}
}
And the bootstrapping logic:
AppModule.config([
'$urlServiceProvider',
($urlService: UrlService) => $urlService.deferIntercept()
]);
getConfig()
.then((config: Config) => {
console.log('CONFIG::::', config);
AppModule.constant('config', config);
setAngularLib(angular);
platformBrowserDynamic([
{
provide: Config,
useValue: config
}
])
.bootstrapModule(Ng2AppModule)
.then(platformRef => {
platformRef.injector.get<NgZone>(NgZone).run(() => {
const urlService = platformRef.injector.get(UIRouter).urlService;
urlService.listen();
urlService.sync();
});
downgradeSharedComponents(AppModule);
});
})
P.S. Existing angularjs routes are working properly, the problem is with routes registered within the ng2+ module.
Any help is appreciated, thanks ^^

Managed to figure this out on my own and wanted to post the answer in case anyone encounter similar issue.
Turned out we had a weird logic in our old angularjs code that was deferring $urlRouter url synchronization:
$urlRouterProvider.deferIntercept();
...
$urlRouter.sync();
Once removed, issue described above disappeared.

Related

#angular/router not working inside an angular.js application

I'm working on migrating little by little a big angular.js application (that uses ui-router) to angular and I opted by using the angular.js application as a base and migrate the different routes one at a time so that once I'm finished I switch everything at once to angular.
These are the steps I've followed:
Bootstap the angular.js application in my main.ts file:
export function bootstrapAngular(extra: StaticProvider[]): any {
setAngularJSGlobal(angular);
if (environment.production) {
enableProdMode();
}
return platformBrowserDynamic(extra)
.bootstrapModule(AppModule)
.catch(err => console.log(err));
}
const downgraded = angular
.module('downgraded', [downgradeModule(bootstrapAngular)])
.directive('appRoot', downgradeComponent({ component: RootComponent, propagateDigest: false }))
;
angular.bootstrap(document, ['app', downgraded.name]);
Inside my index.html
<app id="app"></app>
This works fine.
Inside my main angular.js component I add the tag of my downgraded main Angular component:
<div class="app__view" id="appContent">
<ui-view></ui-view>
<app-root></app-root>
</div>
This is how my main module is configured
const COMPONENTS = [
TestComponent,
RootComponent,
];
#NgModule({
declarations: COMPONENTS,
imports: [
BrowserModule,
NxModule.forRoot(),
RouterModule.forRoot(routes, {
initialNavigation: 'enabled',
useHash: true
})
],
providers: [
{ provide: APP_BASE_HREF, useValue: '/' }
],
entryComponents: COMPONENTS,
exports: COMPONENTS
})
export class AppModule {
ngDoBootstrap(): void { }
}
Everything works fine so far. I can see my angular component inside my angular.js application.
The problem comes when I add the to my main root component
I can see the router-outlet rendering but nothin next to it, eventhough the route matches.
export const routes: Route[] = [
{ path: 'dashboard', component: TestComponent }
];
When I point my browser to /#/dashboard this is the router tracing that I see:
And the test component just doesn't render.
I need some help, can't think of anything else to try.
First of all: if you want to go hybrid and start moving parts of ng1 to ngx, you need to bootstrap your ng1 app from ngx as you did, but not by downgrading:
platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
(<any>platformRef.instance).upgrade.bootstrap(document.body, ['nameOfNg1App']);
});
Than you should provide the entry point for ui-router within your app.component.html:
<div ui-view></div>
You also need to provide an url handling strategy to tell angular, which routes to handle. I had an AppRoutingModule, which was imported by the AppModule. And this one provided the handler:
#NgModule({
imports : [
RouterModule.forRoot(routes, {useHash: true})
],
exports : [
RouterModule
],
// provide custom UrlHandlingStrategy to separate AngularJs from Angular routes
providers: [
{
provide : UrlHandlingStrategy,
useClass: Ng1Ng2UrlHandlingStrategy
}
]
})
export class AppRoutingModule {
}
And the Handling strategy, I used path prefixes to separate ng1 from ngx routes, but you can choose a simpler separation if needed:
import { UrlHandlingStrategy } from '#angular/router';
export class Ng1Ng2UrlHandlingStrategy implements UrlHandlingStrategy {
private ng1Urls: string[];
constructor() {
this.ng1Urls = [
'prefix1',
];
}
shouldProcessUrl(url) {
url = url.toString();
return this.ng1Urls.findIndex(ng1Url => new RegExp(`^\/${ng1Url}([|\?|\/](.*)){0,1}$`).test(url)) === -1;
}
extract(url) {
return url;
}
merge(url, whole) {
return url;
}
}
Oh, and for some reasons I had to stick to # URLs, while running hybrid.
With this setup you start an ngx app, that has a container that runs the ui-router. Within your ng1 app you can then use downgraded ngx components and services.
To have ngx-routes and ng1 routes in parallel, your (ngx) app.component.html consists of
<div ui-view></div>
<router-outlet></router-outlet>
You find more details of this strategy here: https://blog.nrwl.io/upgrading-angular-applications-upgrade-shell-4d4f4a7e7f7b
The solution involved:
Getting rid of UrlHandlingStrategy completely
Disabling initialNavigation
Creating empty routes in both route configurations
Injecting the ng2 router in the ng1 application and adding the following logic
angular.module('app').config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider.state('ng2', { });
$urlRouterProvider.otherwise(($injector, $location) => {
const $state = $injector.get('$state');
const ng2Routes = ['dashboard'];
const ng2Router = $injector.get('ng2Router');
const url = $location.url();
if (ng2Routes.some(feature => url.startsWith('/' + feature))) {
$state.go('ng2');
ng2Router.navigate([url]);
} else {
$state.go('messages');
}
});
}]);

Angular and AngularJS Hybrid Application Routing: Angular component as child state not rendering

first some short introduction to the project and general setup.
It is an Angular/Angular JS application. I integrated Angular couple of weeks ago. In contrast to many different tutorials using the UpgradeModule, I actually had to use the downgradeModule - The project is quite large and UpgradeModule caused a lot of performance issues.
There is an overall Parent State (called app) and I want a Angular Component to be a child of it. According to the docs this should be possible (https://github.com/ui-router/angular-hybrid#limitations)
Limitations:
We currently support routing either Angular (2+) or AngularJS (1.x) components into an AngularJS (1.x) ui-view. However, we do not support routing AngularJS (1.x) components into an Angular (2+) ui-view.
If you create an Angular (2+) ui-view, then any nested ui-view must also be Angular (2+).
Because of this, apps should be migrated starting from leaf states/views and work up towards the root state/view.
The general setup looks like this (simplification):
app.module.ng1.ts
import { AppModule } from './app.module';
const bootstrapFn: any = (extraProviders: Array<StaticProvider>): any => {
return platformBrowserDynamic(extraProviders).bootstrapModule(AppModule);
};
const downgradedModule: any = downgradeModule(bootstrapFn);
const appModule: angular.IModule = angular
.module('app', [
downgradedModule,
// other project modules
]);
app.module.ts
#NgModule({
imports: [
BrowserModule,
UIRouterUpgradeModule.forChild(),
],
declarations: [
AccountNg2Component,
],
providers: [
],
entryComponents: [
AccountNg2Component,
],
})
class AppModule {
public ngDoBootstrap(): void {}
}
export { AppModule };
TheAccountNg2Component is the one I actually want to go to. account.component.ts
#Component({
selector: 'account',
template,
})
class AccountNg2Component {
#Input() public user: any;
constructor() {}
}
export { AccountNg2Component };
There is a parent app state and I want the AccountNg2Component to be a child of it. The state configuration looks like this:
$stateProvider
.state({
parent: 'app',
name: 'account',
url: '/account',
component: AccountNg2Component,
});
Whatever I try it will also result in the following two Errors:
Transition Rejection($id: 0 type: 6, message: The transition errored, detail: TypeError: Cannot read property 'when' of undefined)
TypeError: Cannot read property 'when' of undefined
at Ng2ViewConfig.load (views.js:47)
at eval (views.js:19)
at Array.map (<anonymous>)
at loadEnteringViews (views.js:19)
at invokeCallback (transitionHook.js:104)
at TransitionHook.invokeHook (transitionHook.js:116)
at eval (transitionHook.js:58)
at processQueue (angular.js:17169)
at eval (angular.js:17217)
at Scope.$digest (angular.js:18352)
at Scope.$apply (angular.js:18649)
at eval (angular.js:18952)
at completeOutstandingRequest (angular.js:6428)
at eval (angular.js:6707)
at ZoneDelegate.invokeTask (zone.js:420)
at Object.onInvokeTask (core.js:4961)
at ZoneDelegate.invokeTask (zone.js:419)
at Zone.runTask (zone.js:187)
at ZoneTask.invokeTask (zone.js:495)
at ZoneTask.invoke (zone.js:484)
at timer (zone.js:2053)
I'm probably missing something in the configuration, but I'm not able to figure it out.
What I already tried:
I looked at the sample App (https://github.com/ui-router/sample-app-angular-hybrid) and tried to build it as similar as possible. But they are using the UpgradeModule instead of the downgrade - I don't know if this changes anything for the router.
I tried
Adding state configuration to UIRouterUpgradeModule.forChild() and UIRouterModule.forChild()
Created a "future state" according to https://github.com/ui-router/sample-app-angular-hybrid/blob/master/app/angularModule.ts#L10
Different ways to declare the Account State
Different ways to define the Account Component itself
The error stays always the same, because of that I think I'm just missing some piece in my configuration.
If my description does not help enough, I'll try to setup a jsfiddle or something similar
Update 1:
Ok, I removed the state declaration for the account state from the Angular 1 State Provider and instead only register it in the UIRouterModule. Now at least the error is gone, but the state is not loaded at all (when trying to access it, redirect to default state)
Ok I finally managed to solve the issue, thanks to a tip from a different article (https://stackoverflow.com/a/49568050/4243635)
Just gonna quote it here again:
The Angular bootstrap module needed a parameter of type "UIRouter" in the constructor, otherwise it would not bootstrap its states:
export class AppModule {
constructor(private router: UIRouter) {
// "router" needed in constructor to bootstrap angular states
}
You also need to import UpgradeModule and UIRouterUpgradeModule. So the entire app.module.ts looks like this:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { ServiceBootstrapComponent } from '../../service-bootstrap';
import { AccountNg2Component } from '../../app/pages/account/account.ng2.component';
import { UIRouterUpgradeModule } from '#uirouter/angular-hybrid';
import { AccountState } from '../../app/pages/account/account.states';
import { CommonModule } from '#angular/common';
import { UIRouter, UIRouterModule } from '#uirouter/angular';
import { UpgradeModule } from '#angular/upgrade/static';
#NgModule({
imports: [
CommonModule,
BrowserModule,
UpgradeModule,
UIRouterUpgradeModule,
UIRouterModule.forChild({states: [AccountState]}),
],
declarations: [
ServiceBootstrapComponent,
AccountNg2Component,
],
providers: [
],
entryComponents: [
ServiceBootstrapComponent,
],
})
class AppModule {
constructor(private router: UIRouter) {}
public ngDoBootstrap(): void {}
}
export { AppModule };

Using services in Angular/AngularJS hybrid app (ng-upgrade)

Currently building a slimmed down version of the app for plunker so I can SHOW you my problem, but in case anyone has any tips off the top of their heads in the mean time, I will attempt to describe my problem first.
I'm using ngUpgrade to start bringing a large application from AngularJS to Angular. I've got a core application running using Angular. Briefly it's set up a little like this:
#Component({
selector: '[my-app]',
template: `
<app-main></app-main>
`
})
export class AppComponent {};
#NgModule({
imports: [
BrowserModule,
UpgradeModule,
],
bootstrap: [AppComponent],
declarations: [
AppComponent
],
schemas: [
CUSTOM_ELEMENTS_SCHEMA
]
})
export class AppModule {
constructor(public upgrade: UpgradeModule) { }
}
export const Ng1AppModule = angular.module(
'mainApp',
[
'feature.one'
]
);
platformBrowserDynamic().bootstrapModule(AppModule).then(ref => {
ref.instance.upgrade.bootstrap(document.body, [Ng1AppModule.name], {});
});
It successfully bootstraps itself and runs a root component which essentially loads the old AngularJS application. So far no major problems.
The AngularJS application has dependencies on a lot of custom feature modules which I now need to convert to Angular.
On one of the feature modules I want to convert a service. It's now an Angular #Injectable built in typescript and it is assigned to and AngularJS module like so:
export const Ng1FeatureModule = angular
.module('feature.one', ['ngCookies'])
.service('UpgradedService', downgradeInjectable(UpgradedService) as any);
This service requires a dependency from a service I have not even converted yet.
Example:
#Injectable()
export class UpgradedService{
public var1: string;
constructor(private nonconvertedNG1Service: NonconvertedNG1Service) {
this.var1 = nonconvertedNG1Service.get();
}
public getVar1() {
return this.var1;
}
}
How do I need to set things up so that my example app uses 'UpgradedService' and UpgradedService is able to use NonconvertedNG1Service?

downgradeModule doesn't start Angular5 part in hybrid app

Angular5 introduced a new way of upgrating app from AngularJS to Angular -
downgradeModule. It should resolve an issue with to eager change detection in this kind of hybrid application. So far, in Angular4 I used UpgradeModule successfully, but it caused some performance issue because of change detections. Now I'm trying to use downgradeModule. In this approach AngularJS is started first, next downgradeModule starts Angular. In this way AngularJS in running outside of AngularZone, what should calm down change detection.
main.ts which is pointed in .angular-cli.json as "main"
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app.module';
import {enableProdMode, StaticProvider} from '#angular/core';
import { downgradeModule } from '#angular/upgrade/static';
enableProdMode();
declare var angular: any;
const bootstrapFn = (extraProviders: StaticProvider[]) => {
const platformRef = platformBrowserDynamic(extraProviders);
return platformRef.bootstrapModule(AppModule);
};
const myDowngradedModule = downgradeModule(bootstrapFn);
angular.bootstrap(document.documentElement, [
'legacyApp',
myDowngradedModule
]);
Now, AngularJS starts well, but Angular does not. No error on console, no tips. Just main selector eg. <my-app> is not evaluated.
Nothing changed in app.module.ts in context of previous working version.
#NgModule({
imports: [
CommonModule,
BrowserModule,
UpgradeModule,
RouterModule.forRoot([], { initialNavigation: false })
],
providers: [{provide: APP_BASE_HREF, useValue : '/shop/' }],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {
ngDoBootstrap() {}
}
I use some draft Angular doc, because the major one doesn't say anything about downgradeModule.
https://pr18487-aedf0aa.ngbuilds.io/guide/upgrade-performance
Does anyone know why Angular5 part is not starting?
Only for information purpose, the previous look of main.ts with UpgradeModule which worked quite well, but change detection.
platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
upgrade.bootstrap(document.documentElement, ['legacyApp']);
platformRef.injector.get(Router).initialNavigation();
});
LancerX, have you tried adding AppComponent to the entryComponents in AppModule?
#NgModule({
imports: [
CommonModule,
BrowserModule,
UpgradeModule,
RouterModule.forRoot([], { initialNavigation: false })
],
providers: [{provide: APP_BASE_HREF, useValue : '/shop/' }],
declarations: [ AppComponent ],
entryComponents: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {
ngDoBootstrap() {}
}
It may be because of the AoT-Compilation. We had a similar Problem and solved it by deactivating aot.
Also see https://pr18487-aedf0aa.ngbuilds.io/guide/upgrade-performance#using-ahead-of-time-compilation-with-hybrid-apps
I had this same issue, and it was because I registered the downgraded component with a bad name. I registered it like this:
angular.module("myModule").directive("my-component", downgradeComponent({ component: MyComponent}));
But it should have been this:
angular.module("myModule").directive("myComponent", downgradeComponent({ component: MyComponent}));
So the component was never initialized because the name was wrong. And because the downgraded module is lazy-loaded (it isn't loaded until one of the components are loaded), the module was never initialized either. Fixing the directive name fixed the problem.

Angular2 bootstrap from outside typescript file, directly from html page

I have existing website, which is build with angular1+requirejs and php. I would like to add angular2 (which I have already added, using angular2-cli).
I don't need angular1 to communicate with angular2, so we don't have to do ng-upgrade
I want to bootstrap angular2 components outside app component typescript file.
I'm bit confused on how to do this, because everything is in typescript and after compiled, they are completely different.
I'm trying to load different component per page, sometime one and sometime more then one.
Actually, first to all you need to provide more information. But, on the big picture, you have create a root module and declare component that belong to it, the same for directives and so on. Ex.
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import
{ AppComponent } from './app.component';
#NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
bootstraping the module:
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
anyway, you can check this to get some idea ngModule
This is how to boostrap with javascript.
Creating module:
(function(app) {
app.AppModule =
ng.core.NgModule({
imports: [ ng.platformBrowser.BrowserModule ],
declarations: [ app.AppComponent ],
bootstrap: [ app.AppComponent ]
})
.Class({
constructor: function() {}
});
})(window.app || (window.app = {}));
bootstraping:
(function(app) {
document.addEventListener('DOMContentLoaded', function() {
ng.platformBrowserDynamic
.platformBrowserDynamic()
.bootstrapModule(app.AppModule);
});
})(window.app || (window.app = {}));

Resources