0

What is a method to refresh a route in Angular 2 programmatically in order to trigger onInit hook?

6
  • Why would you want that? Commented Feb 5, 2016 at 20:33
  • 1
    I need to refresh the page after get authorization token from server if authorization token expires. I have got method for that but don't know how to refresh the current view after getting right token. Commented Feb 5, 2016 at 21:53
  • You could just do data-binding. I still don't see a necessity to reload anything. Just use a share service with an EventEmitter to allow components to subscribe changes. Commented Feb 5, 2016 at 21:56
  • Thanks for that. It is a good solution but with more code. Maybe there is a single method to just refresh the current route. Commented Feb 5, 2016 at 22:02
  • @KrzysztofSaja have you got answer ? Commented Feb 24, 2016 at 10:21

2 Answers 2

1

Maybe there is a single method to just refresh the current route.

From:

https://angular.io/docs/ts/latest/api/router/Router-class.html

renavigate() : Promise<any>

Navigates to either the last URL successfully navigated to, or the last URL requested if the router has yet to successfully navigate.

Inject the router and call the renavigate() method:

this._router.renavigate();

Sign up to request clarification or add additional context in comments.

4 Comments

I've already tried this one but router.renavigate() seems to work only if url is changed. Otherwise it is like double clicking a route link - it doesn't do anything.
The same as with renavigate
same does't work properly. on clicking back button of browser.
@all Take a look at github.com/angular/angular/issues/13831#issuecomment-319634921 for how to trick the router into reloading the current view
0

works for angular 5+ :

1) add runGuardsAndResolvers to your route:

const routes: Routes = [   { path: '', component: YourComponent, runGuardsAndResolvers: "always" } ]

2) add onSameUrlNavigation property to routes import

@NgModule({
  imports: [RouterModule.forRoot(routes, {
    onSameUrlNavigation: 'reload'
  })],
  exports: [RouterModule]
})

3) now navigating to your url using navigateByUrl('current url') reloads the page for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.