4

I have a view which uses service to load a list of items. I'm always displaying only one item, moving between items with << >> buttons.

Is there any way to change address in browser's address bar and to add record to browser's history without triggering Angular's routing system?

I know that if I use:

location.go('users/3');

it will do above-mentioned things, but it also triggers Angular's route system, which in turn calls my services again.

Edit:

it seems like location's function

location.replaceState('users/3');

is getting close to what I want to do - it changes url in browser without triggering any Angular internals, unfortunately it replaces latest location in history instead of pushing the new one at the top.

5
  • 1
    Like @Günter Zöchbauer said, if you declare the provider ONLY in a top level it doesn't matter how many times you inject it, it won't get recreated. Check this to see if it helps to what you are looking for: angular.io/docs/ts/latest/api/router/AuxRoute-class.html there's no much documentation yet but I believe it is meant for these kind of scenarios. Commented Jan 19, 2016 at 15:41
  • There was maybe some misunderstanding. The service is not recreated, but called every time route is triggered - Component where the service is injected is recreated (ngOnInit called). But again, I've found location.replaceState which does the more important half of what I want to accomplish, now I'd like to find how to solve history being overwritten when calling replaceState function Commented Jan 19, 2016 at 16:36
  • 1
    Yea, I do believe AuxRoute was meant for what you need to do. Commented Jan 19, 2016 at 16:47
  • 1
    You don't provide information about how that service is integrated into your application. canReuse stackoverflow.com/questions/33648355/… might also help. angular.io/docs/ts/latest/api/router/CanReuse-interface.html Commented Feb 10, 2016 at 14:33
  • 1
    @GünterZöchbauer could you add the canReuse part also to your answer as an alternative, it was what I was looking for and I almost missed it since it was hidden in the comments. Commented Apr 13, 2016 at 17:47

1 Answer 1

1

If you don't add the service to the components provider: list you won't get a new instance for this service. Make the service global instead by only registering in bootstrap(AppComponent, [MyGlobalService]).

Implementing CanReuse see also Angular 2: Swapping between different components without destroying them might help to prevent re-initializing components when the same route is reused.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.