Home > Web Front-end > JS Tutorial > body text

Angular route reuse implementation strategy

小云云
Release: 2018-01-27 14:23:43
Original
1443 people have browsed it

This article mainly introduces the Angular routing reuse strategy. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

1. Introduction

Routing operates statelessly on components during execution, that is, the component status is also deleted when the route exits; of course, in most cases This is reasonable given the scenario.

But sometimes some special needs can cause people to be in a semi-dead state. Of course, this is all for the sake of user experience; a very common scenario is that users search for products through keywords on the mobile terminal, and they are still alive. The list usually moves to the next page automatically. At this time, when the user finally scrolls to the second page and finds the product he wants to see, he is routed to the product details page, and then backs up... the user is confused.

Angular routing and components form a relationship from the beginning through RouterModule.forRoot. When the route hits, ComponentFactoryResolver is used to build the component. This is the essence of routing.

Each route is not necessarily a one-time consumption. Angular uses RouteReuseStrategy to run through the routing state and decide how to build components; of course, by default (DefaultRouteReuseStrategy), as mentioned at the beginning, nothing is processed.

RouteReuseStrategy has been experimental since 2 and is still so now. It should be trustworthy for so long.

2. RouteReuseStrategy

RouteReuseStrategy I call it: route reuse strategy; it is not complicated and provides several easy-to-understand methods:

  • shouldDetach Whether to allow route reuse

  • store Will be triggered when the route leaves, store the route

  • shouldAttach Whether to allow route restoration

  • retrieve Get stored route

  • shouldReuseRoute Enter route trigger, whether to reuse the same route

This looks like a timeline relationship, in vernacular it looks like this: Set the route/list to allow reuse (shouldDetach), and then store the route snapshot in the store; when shouldReuseRoute is established That is: after encountering the /list route again, it means that the route needs to be reused. First, determine whether shouldAttach allows restoration, and finally get the routing snapshot from retrieve and build the component.

When we understand this principle, if we take the problem returned by the search list at the beginning, it becomes very easy to solve.

3. An example

As explained above, you only need to implement the RouteReuseStrategy interface to customize a route utilization strategy.

1. Create a strategy

import {RouteReuseStrategy, DefaultUrlSerializer, ActivatedRouteSnapshot, DetachedRouteHandle} from '@angular/router';

export class SimpleReuseStrategy implements RouteReuseStrategy {

  _cacheRouters: { [key: string]: any } = {};

  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return true;
  }
  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
    this._cacheRouters[route.routeConfig.path] = {
      snapshot: route,
      handle: handle
    };
  }
  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return !!this._cacheRouters[route.routeConfig.path];
  }
  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
    return this._cacheRouters[route.routeConfig.path].handle;
  }
  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    return future.routeConfig === curr.routeConfig;
  }
}
Copy after login

Define a _cacheRouters for caching data (routing snapshot and current component instance object).

  • shouldDetach returns true directly, indicating that reuse is allowed for all routes.

  • store will be triggered when the route leaves. Use path as key to store routing snapshot & component current instance object; path is equivalent to the configuration in RouterModule.forRoot.

  • shouldAttach If the path exists in the cache, it is considered that the route is allowed to be restored.

  • retrieve Get the snapshot from the cache, if not, return null

  • shouldReuseRoute Enter the routing trigger to determine whether it is the same route

2. Register

Finally register the policy to the module Among them:

providers: [
 { provide: RouteReuseStrategy, useClass: SimpleReuseStrategy }
]
Copy after login

Suppose we have such a routing configuration:

RouterModule.forRoot([
 { path: 'search', component: SearchComponent },
 { path: 'edit/:id', component: EditComponent }
])
Copy after login

The search component is used for search actions, and jumps to the edit page based on the search results, and then returns to the last search results after saving. status (I will not post this part of the code, please see plnkr).

4. Conclusion

The above is just a simple introduction. In fact, the judgment of reuse will be more complicated, such as scroll bar position, cache cleaning, etc.

Make good use of this routing reuse strategy mechanism to solve many Web experience problems.

Related recommendations:

angular2 routing preloading example detailed explanation

The above is the detailed content of Angular route reuse implementation strategy. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!