Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel (Asynchronous Non Blocking) Routing In Angular 2/4

The application has a page with 2 to 3 category buttons. Basically, button click will pull the list of items in each category, the page should be shown once API fetched data is available.

I have designed angular 2 app routes with resolve API calls and I should not block the entire page with spinner when a page loads as we are migrating the application functionality to angular 4.

When a user clicks on one category, if the response is delayed he may click the other category. When he navigates back he would be expecting the data to be loaded in previously clicked category but Angular 2/4 cancels the route due to Navigation ID does not match with the current route

To have a better understanding, kindly see the plnkr link below. http://embed.plnkr.co/UiyhZWCl63Tfq41WY48q/

Click on the planet and people concurrently, observe that only one of the section loads and other section doesn't load the data. If you do inspect you can see NavigationCancel event is thrown

like image 221
newstackoverflowuser5555 Avatar asked Jun 27 '17 11:06

newstackoverflowuser5555


People also ask

What is ActivatedRoute in Angular?

What is an activated route? The Angular Docs define the ActivatedRoute as. A service that is provided to each route component that contains route specific information such as route parameters, static data, resolve data, global query params and the global fragment.

What is routing and types of routing in Angular?

Routing in Angular allows the users to create a single-page application with multiple views and allows navigation between them. Users can switch between these views without losing the application state and properties.


1 Answers

Not sure If am qualified to explain how resolver works for router on Angular 2, but just went through again their document.

In summary, you want to delay rendering the routed component until all necessary data have been fetched.

You need a resolver.

So as my understanding, the resolver will help in case you want to switch the view totally and fetch the data before switching. So the data is ready the moment the route is activated. This also allows you to handle errors before routing to the component. Think of master-detail layout whereby you click into an item, it navigates to a detail view. There's no point in navigating to a detail for an id that doesn't have a record and it's better to send the user back to the list.

Your case is not a common case when you want to display different outlet base on the route. And you want the moment you click into people/planet, it will render the component directly and start fetching the data. You might want to show the placeholder 'Loading...' as well. So I suggested to use ngOnInit hook for that purpose.

Working plunker: https://embed.plnkr.co/rSEjb46WI09PsOtClJn5/

like image 142
trungk18 Avatar answered Oct 18 '22 02:10

trungk18