Home > Web Front-end > JS Tutorial > How to reuse strategies in Angular routing

How to reuse strategies in Angular routing

一个新手
Release: 2017-10-24 11:04:17
Original
1774 people have browsed it

1. Introduction

Routing operates statelessly on components during execution, that is, the component status is also deleted when the routing exits; of course, this is reasonable in most scenarios.

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, everything No processing is performed.

RouteReuseStrategy It has been experimental since 2, and it is still like this. 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. Storage route

  • shouldAttach Whether to allow restoration of route

  • retrieve Get storage route

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

This looks like a timeline relationship, In a vernacular, it looks like this: Set route /list to allow reuse (shouldDetach), and then store the route snapshot in store; when shouldReuseRoute is established: when the /list route is encountered again, it indicates that the route needs to be reused, first determine whether shouldAttach is allowed to be restored, and finally retrieve Get the route snapshot 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 Directly return true to allow reuse of all routes

  • store Fires 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 path is 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. Registration

Finally register the strategy into the module:

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

Assume we have such a routing configuration:

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

Search component is used for search action, and jump to the edit page based on the search results, and then return to the state of the last search results after saving (I will not post this part of the code, I am interested in seeing 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.


The above is the detailed content of How to reuse strategies in Angular routing. 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