3

I am migrating my app from Angular 1.X to Angular 2.0 and I am having thoughts about routing solution while / after migration process.

I am currently using ui-router, with resolve in order to pass data for each route.

After some reading I came across this post. As far as I understand, there is no resolve in the new router. I now have two choices:

  1. Continue using my current ui-router with my hybrid ng1-2 app (is it possible?), and bring each route's data via router's resolve. Will it work?

  2. Change routing and use the new Component Router. This will make the step-by-step upgrade harder, because I will have to change my current Angular 1.X data fetching to be inside each controller / directive + I won't have Angular 2's @CanActivate which will wait for data to be resolved.

Which option is better? Is there another option? What will work here?

Thanks!

Community
  • 1
  • 1
Yaniv Efraim
  • 6,633
  • 7
  • 53
  • 96

1 Answers1

0

I encountered the same issue at work. I tried many things, but in the end I used a service:

var data = {
  'foo': 'bar'
}

export const StateData = {
  data: data
};

So now at the top of my component I can import the service:

import { StateData } from '/services/StateService.ts';

Then I can set and get data from the service by simply doing:

StateData.data.foo = "something other than bar"

Now when you switch routes, you can retrieve the new updated data within the constructor() or afterViewInit() methods.

*An added bonus of using the StateService is that you can bind your data between all components by simply adding the following method (you can name it whatever):

getStateData(key) {
    return StateData.data[key];
}

You can call this method from the dom itself by doing the following:

{{getStateData('foo')}} --> will print out the value "bar"

Now if you change the value of foo within the service in a different component, it will change in the dom, since getStateData() is called whenever a change occurs and the service only loads once on page load.

I believe the init and afterViewInit methods are the reason as to why they have not added resolve to the new router, or maybe they still haven't released the version with it yet.

I hope this helps you out. I do not think using Angular 1.x + Angular 2.0 would be easy, nor would it be fun lol

I recently rebuilt my personal site in angular 2.0. The code is public, so you can check it out. If you look at contactCard.ts, contact-card.html and StateService.ts you can see it in action. Here is the repo:

https://github.com/YashYash/portfolio

user15163
  • 641
  • 1
  • 7
  • 10