Navigation is very simple, it is just switching between different pages, and routing is a kind of navigation.
A page corresponding to a url is a component in angular2. Define a rule.
Basic knowledge
Most applications with routing need to add an element under the tag to tell the router how to synthesize the URL for navigation.
The routing is introduced from the @angular/router package.
Routing needs to be configured. What this configuration requires is the RouterModule module.
A routing configuration
You cannot use slashes/starts in the path.
The order in which these routes are defined is designed intentionally so. The router uses the first matcher priority strategy to match the route, so the specific route should be placed in front of the general route. In the above configuration, the route with a static path is placed in front and the empty path is followed by the route, so it will be used as the default route. The wildcard route is placed at the end because it is the most common route and should only be matched if no other matching route is found in front.
const appRoutes: Routes = [ { path:'',// empty path matches the default path of routes at each level. It also supports adding routes without extending URL paths. component: DashboardComponent },{ path: 'dashboard', component: DashboardComponent }, { path: 'loopback', component: LoopbackComponent }, { path: 'heroparent', component: HeroParentComponent }, { path:'version', component: VersionParentComponent }, { path: '**',// ** means that the route is a wildcard path. If the current URL cannot match the path in any route we have configured, the router will match this one. This feature is very useful when you need to display a 404 page or redirect to another route. component: DashboardComponent, } ]; export const appRoutingModule: ModuleWithProviders = (appRoutes);
RouterOutlet - Router socket
Displays the router-generated view. Display the child route somewhere in the location where the parent route is displayed.
Routing module
The initial route was written directly in the file, and like this, we can implement simple navigation.
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './'; import { CrisisListComponent } from './'; import { HeroListComponent } from './'; const appRoutes: Routes = [ { path: 'crisis-center', component: CrisisListComponent }, { path: 'heroes', component: HeroListComponent } ]; @NgModule({ imports: [ BrowserModule, FormsModule, (appRoutes) ], declarations: [ AppComponent, HeroListComponent, CrisisListComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
But this is inconvenient, so we need to separate routes and reconstruct our own routing module. like this:
const appRoutes: Routes = [ { path:'', component: DashboardComponent },{ path: 'dashboard', component: DashboardComponent }, { path: 'loopback', component: LoopbackComponent }, { path: 'heroparent', component: HeroParentComponent }, { path:'version', component: VersionParentComponent }, { path: '**', component: DashboardComponent, } ]; export const appRoutingModule: ModuleWithProviders = (appRoutes);
We can also write multiple routing modules. But we have to do imports:[appRoutingModule] in.
Component routing
We need to divide some feature areas and make them into our own separate modules. Must be like hero module. Here we need hero's separate navigation, which is the component routing.
Level-level routing
@NgModule({ imports: [ ([ { path: 'heroes', component: HeroListComponent }, { path: 'hero/:id', component: HeroDetailComponent }, { path:'heroform', component: HeroFormComponent }, ]) ], exports: [ RouterModule ] }) export class HeroRoutingModule { }
We also have another type of routing organization method, the form of routing tree.
const crisisCenterRoutes: Routes = [ { path: '', redirectTo: '/crisis-center', pathMatch: 'full' }, { path: 'crisis-center', component: CrisisCenterComponent, children: [ { path: '', component: CrisisListComponent, children: [ { path: ':id', component: CrisisDetailComponent, }, { path: '', component: CrisisCenterHomeComponent } ] } ] } ]; @NgModule({ imports: [ (crisisCenterRoutes) ], exports: [ RouterModule ] }) export class CrisisCenterRoutingModule { }
Redirecting routing
Add a redirect route that quietly translates the initial relative URL (") into the default path (/crisis-center).
{ path: '', redirectTo: '/crisis-center', pathMatch: 'full' },
Router Guard
Introduction
Router guards, which are not valid for all navigation in this route, have some preconditions, and can only be navigated to this page when these preconditions are met.
Guards can be added to the routing configuration for processing. The guard can return a boolean value. When true, the navigation process continues. When false, the navigation is cancelled. Of course, it can also be navigated to other pages at this time. It can also return an Observable<boolean> or Promise<boolean>, and the router will wait for the observable object to be parsed to true or false.
The router supports multiple guards
useCanActivateto handle navigation to a route.
useCanActivateChildHandle navigation to subroutines.
useCanDeactivateto handle the situation where it leaves from the current route.
useResolveGet routing data before routing is activated.
useCanLoadTo handle the situation of asynchronous navigation to a feature module.
Rules of use
At each level of hierarchical routing, we can set up multiple guards. The router will first check the CanDeactivate daemon conditions in the order of checking from the bottom to the top from the deepest subroutine. It then checks the CanActivate guard in order from top to bottom. If any guard returns false, other unfinished guards will be cancelled, and the entire navigation will be cancelled.
CanActivate
Using CanActivate to handle navigation routing, you need to add the import AuthGuard class in the routing configuration, modify the management route and reference AuthGuard through the CanActivate attribute.
The specific guard rules depend on the implementation of the AuthGuard class. The AuthGuard class needs to inherit the CanActivate class:export class AuthGuard implements CanActivate {}
import { AuthGuard } from '../'; const adminRoutes: Routes = [ { path: 'admin', component: AdminComponent, canActivate: [AuthGuard], // Focus children: [ { path: '', children: [ { path: 'crises', component: ManageCrisesComponent }, { path: 'heroes', component: ManageHeroesComponent }, { path: '', component: AdminDashboardComponent } ], } ] } ]; @NgModule({ imports: [ (adminRoutes) ], exports: [ RouterModule ] }) export class AdminRoutingModule {}
CanActivateChild Guarding Self-Route
Just as we can guard routes through CanActivate, we can also protect subroutines through CanActivateChild. The CanActivateChild guard works very similarly to the CanActivate guard, except that it runs before each subroutine is activated. We protect the management feature module from unauthorized access, and we can also protect subroutines in the feature module.
This is relatively simple to use, you only need to add it to the configuration of the subroutines that need to be guarded. The AuthGuard class needs to inherit the canActivateChild class:export class AuthGuard implements canActivateChild {}
const adminRoutes: Routes = [ { path: 'admin', component: AdminComponent, canActivate: [AuthGuard], children: [ { // No component routing, equivalent to grouping path: '', canActivateChild: [AuthGuard], // Guardian subroutine route children: [ { path: 'crises', component: ManageCrisesComponent }, { path: 'heroes', component: ManageHeroesComponent }, { path: '', component: AdminDashboardComponent } ] } ] } ];
CanDeactivate Handles unsaved changes
In the real world, we have to accumulate user changes first. We may have to perform cross-field verification, we may have to find a server to perform verification, and we may have to save these changes into a pending state until the user either confirms or cancels all changes as a group.
When a user wants to navigate outside, how should he deal with these changes that have not been reviewed or saved? We can't leave immediately and don't care about the risk of losing these changes, which is obviously a bad user experience.
We should pause and let the user decide what to do. If the user chooses Cancel, we stay and allow more changes. If the user selects confirm, save it.
We can continue to postpone navigation before saving successfully. If we let the user move to the next interface immediately and the save fails (probably because the data does not comply with the validity rule), we will lose the context of the error.
We can't block it while waiting for the server's reply - this is impossible in the browser. We can only stop navigation asynchronously before waiting for the server to reply.
We need the CanDeactivate guard.
Resolve
The main implementation is to pre-load routing information before navigation. It can be done that when you really need to navigate into this details page, you no longer need to obtain data. It was loaded in advance.
The service can implement the Resolve guard interface to synchronously or asynchronously resolve routed data.
CanLoad - Protect Feature Module Loading
premise
Asynchronous routing, as long as it is lazy to load feature areas. The benefits of doing this:
- You can continue to build feature areas, but no longer increase the initial package size.
- The feature area is loaded only when the user requests it.
- Speed up loading for users who only access certain areas of the application.
The router uses the loadChildren property to map the bundle files we want to load lazy, here is the AdminModule.
const appRoutes: Routes = [ { path: 'admin', loadChildren: 'app/admin/#AdminModule', } ];
Map to files we built in the management feature area before. After the file path, we use # to mark the end of the file path and tell the router the name of the AdminModule. Open the file and we will see that it is the name of the module class we exported.
export class AdminModule {}
Introduction
We have made CanAcitvate secure AdminModule, which blocks anonymous access to the administrative feature area. We can load the management class route asynchronously when requesting, check the user's access rights, and jump to the login page if the user is not logged in. But more ideally, we only load the AdminModule if the user is already logged in, and we don't release it until it's loaded.
We can use the CanLoad guard to ensure that the AdminModule is loaded only once when the user has logged in and tries to access the administrative feature area.
Several concepts
Componentless routing
Componentless routing, no component grouping. See AdminComponent
Under subroutine, we have a subroutine with path and children, but it does not use component. This is not a misstep in configuration, but a component-free routing.
const adminRoutes: Routes = [ { path: 'admin', component: AdminComponent, children: [ { // Componentless routing path: '', children: [ { path: 'crises', component: ManageCrisesComponent }, { path: 'heroes', component: ManageHeroesComponent }, { path: '', component: AdminDashboardComponent } ] } ] } ]; @NgModule({ imports: [ (adminRoutes) ], exports: [ RouterModule ] }) export class AdminRoutingModule {}
Preload: Load feature areas in the background
Each time the navigation occurs successfully, the router will view the configuration of the lazy loaded feature area and react according to the provided policy. The router supports two preload policies by default:
- No preloading at all, this is the default value. The lazy load feature area is still loaded as needed.
- Preload all lazy loaded feature areas.
The router also supportsCustomize preloading policies, used to finely control preloading.
Customize preloading policies
Route Data Starts Preloading
There is a parameter preload boolean value, if it is true, the built-in Router is called
The provided load function pre-actively loads these feature modules.
Create a custom policy
We will need to implement the abstract class PreloadingStrategy and preload methods. The router calls the preload method when loading the feature modules asynchronously and deciding whether to preload them. The preload method has two parameters. The first parameter Route provides routing configuration, and the second parameter is a function that preloads the feature module.
Link parameter array
The link parameter array saves the required components when routing navigation:
- The path to the route to the target component (path)
- Required routing parameters and optional routing parameters, which will enter the URL of the route
.We can bind the RouterLink directive to an array, like this:
<a [routerLink]="['/heroes']">Heroes</a>
.When specifying routing parameters, we write an array of two elements, like this:
(['/hero', ]);
.We can provide optional routing parameters in the object, like this:
<a [routerLink]="['/crisis-center', { foo: 'foo' }]">Crisis Center</a>
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.