How to route via code in an Angular hybrid app

739 Views Asked by At

I'm working on a Hybrid Angular/AngularJS app. The main AppModule is Angular module that uses AppRoutingModule that uses a given state. Something like that:

AppModule:

imports: [AModule, BModule, AppRoutingModule, ...]

AppRoutingModule:

imports: [UIRouterUpgradeModule.forRoot(states: some_state)]

States:

export const some_state: [
  {
    name: 'a',
    url: '/a'
    views: {
            main: {component: AComponent}
    }
  },
  {
    name: 'b',
    url: '/b'
    views: {
            main: {component: BComponent}
    }
  }
]

What I want to do - say I'm in a BComponent, I want to navigate to AComponent. In a pure angular component I would use the Router from the RouterModule (forRoot in AppModule and forChild in child modules). Something like router.navigateToURL('...')

Now I'm using UIRouterUpgradeModule and I could not find how to do it. Any help will be great thanks!

2

There are 2 best solutions below

1
On

In your component, first declare router in constructor like shown below :

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  // ...
})
export class AppComponent {

  constructor(private router: Router) {}

  // ...
}

Then create a function that will be used whenever route change is required, you can bind this function to any event like button click to see required changes :

changeRoute() {
  this.router.navigateByUrl('/b');
}
0
On

So the thing that worked for me is this: Imported the StateService from @uirouter/core in the constructor like so:

constructor(private stateService: StateService)

and in my method did the following:

stateService.go('URL_TO_GO_TO');

This worked for me and I was redirected as wanted.