详解Angular路由之路由守卫(2)
配置路由,同样先加到provider,再配置路由。
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { ProductComponent } from './product/product.component'; import { Code404Component } from './code404/code404.component'; import { ProductDescComponent } from './product-desc/product-desc.component'; import { SellerInfoComponent } from './seller-info/seller-info.component'; import { ChatComponent } from './chat/chat.component'; import { LoginGuard } from './guard/login.guard'; import { UnsaveGuard } from './guard/unsave.guard'; const routes: Routes = [ { path: '', redirectTo : 'home',pathMatch:'full' }, { path: 'chat', component: ChatComponent, outlet: "aux"},//辅助路由 { path: 'home', component: HomeComponent }, { path: 'product/:id', component: ProductComponent, children:[ { path: '', component : ProductDescComponent }, { path: 'seller/:id', component : SellerInfoComponent } ] ,canActivate: [LoginGuard], canDeactivate: [UnsaveGuard]}, { path: '**', component: Code404Component } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: [LoginGuard,UnsaveGuard] }) export class AppRoutingModule { }
效果:
点ok离开当前页面,cancel留在当前页面。
四、Resolve守卫
http请求数据返回有延迟,导致模版无法立刻显示。
数据返回之前模版上所有需要用插值表达式显示某个controller的值的地方都是空的。用户体验不好。
resolve解决办法:在进入路由之前去服务器读数据,把需要的数据都读好以后,带着这些数据进到路由里,立刻就把数据显示出来。
实例:
在进入商品信息路由之前,准备好商品信息再进入路由。 拿不到信息,或者拿信息出问题了,直接跳到错误信息页面,或者弹出提示,就不再进入目标路由。
先在product.component.ts中声明商品信息类型。
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { ProductComponent } from './product/product.component'; import { Code404Component } from './code404/code404.component'; import { ProductDescComponent } from './product-desc/product-desc.component'; import { SellerInfoComponent } from './seller-info/seller-info.component'; import { ChatComponent } from './chat/chat.component'; import { LoginGuard } from './guard/login.guard'; import { UnsaveGuard } from './guard/unsave.guard'; const routes: Routes = [ { path: '', redirectTo : 'home',pathMatch:'full' }, { path: 'chat', component: ChatComponent, outlet: "aux"},//辅助路由 { path: 'home', component: HomeComponent }, { path: 'product/:id', component: ProductComponent, children:[ { path: '', component : ProductDescComponent }, { path: 'seller/:id', component : SellerInfoComponent } ] ,canActivate: [LoginGuard], canDeactivate: [UnsaveGuard]}, { path: '**', component: Code404Component } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: [LoginGuard,UnsaveGuard] }) export class AppRoutingModule { }
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:http://www.heiqu.com/77.html