Angular 2: uiRouter get current state params in root component

Issue

How can i get params in root component? (app.component.ts)

I have such app.component.ts (i’m using Angular/Cli):

import {Transition} from "@uirouter/angular";
...

export class AppComponent {
  id: any;

  constructor(private trans: Transition) {
    this.id = trans.params().someId;
  }
}

but i get:

ERROR Error: No provider for Transition!

But if i use the same logic in any inner component (which has route) – everything is fine. What i do wrong?

Also!

I’m using ngx-restangular. And i have in app.module.ts:

// Function for settting the default restangular configuration
export function RestangularConfigFactory (RestangularProvider, authService) {
  RestangularProvider.setBaseUrl('http://api.test.com/v1');

  // This function must return observable
  var refreshAccesstoken = function () {
    // Here you can make action before repeated request
    return authService.functionForTokenUpdate();
  };

  RestangularProvider.addErrorInterceptor((response, subject, responseHandler) => {
    if (response.status === 403) {

      /*Here somehow I need to get route params too, is it possible, and how?*/

      refreshAccesstoken()
      .switchMap(refreshAccesstokenResponse => {
        //If you want to change request or make with it some actions and give the request to the repeatRequest func.
        //Or you can live it empty and request will be the same.

        // update Authorization header
        response.request.headers.set('Authorization', 'Bearer ' + refreshAccesstokenResponse)

        return response.repeatRequest(response.request);
      })
      .subscribe(
        res => responseHandler(res),
        err => subject.error(err)
      );

      return false; // error handled
    }
    return true; // error not handled
  });
}

// AppModule is the main entry point into Angular2 bootstraping process
@NgModule({
  bootstrap: [ AppComponent ],
  imports: [ 
    // Importing RestangularModule and making default configs for restanglar
    RestangularModule.forRoot([authService], RestangularConfigFactory),
  ],
})

how i can get there route params as well?

Solution

Option 1: route to root component

If you currently have in index.html:

<root-component></root-component> <!-- has a ui-view inside it -->

and

bootstrap: RootComponent

You can switch to bootstrapping a UIView:

<ui-view></ui-view>

and

bootstrap: UIView

then route to your root component

const rootState = { component: RootComponent }

then your root component will be able to inject the initial Transition

See the sample app for an example:

https://github.com/ui-router/sample-app-angular/blob/e8f8b6aabd6a51bf283103312930ebeff52fe4c3/src/app/app.module.ts#L37

https://github.com/ui-router/sample-app-angular/blob/e8f8b6aabd6a51bf283103312930ebeff52fe4c3/src/app/app.states.ts#L7-L18

Option 2: Use the transition start observable

class RootComponent {
  constructor(router: UIRouter) {
    this.subscription = router.globals.start$.subscribe((trans: Transition) => console.log(trans)))
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Option 3: Use a transition hook

If you’re trying to do some action for the initial transition, do this in a transition hook

function configFn(router: UIRouter) {
  router.transitionService.onStart({}, function(trans: Transition) {
    if (trans.$id === 0) {
      return somepromise; // Allows async, etc
    }
  }
}

Answered By – Chris T

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.