【Angular】Angular4路由的改变
2017-08-25 00:00
615 查看
原文地址:https://yakovfain.com/2017/03/26/angular-4-changes-in-the-router/
Angular4在路由中有一些有用的更改。我们来看一下在路由的CanDeactivete中接收参数的变化。(看<a href="https://yakovfain.com/2016/07/20/angular-2-guarding-routes/" terget="_blank">这里</a>)
路由可以使用ActivatedRoute的快照属性或通过订阅其属性参数来接收参数。现在有一个属性paramMap,可以通过使用get()方法获取一个特定的参数,或者通过调用getAll()获取所有的参数。
以下是接收上一个路由中没有更改的参数ID的方法:
如果路由在上一个路由中已经更改了,(看<a href="https://yakovfain.com/2016/11/20/angular-2-implementing-master-detail-using-router/" target="_blank">这里</a>)你可以像下面这样订阅id的流:
CanDeactivate守卫现在允许您更具体,有条件地禁止从路由导航,具体取决于用户计划导航的位置。接口CanDeactivate现在有一个可选参数nextState,您可以检查以决定是否要禁止导航。下一个代码片段只显示用户尝试导航到由路径“/”表示的归属路由时,显示警告弹出窗口。导航到任何其他路线仍然没有保护。
Angular4在路由中有一些有用的更改。我们来看一下在路由的CanDeactivete中接收参数的变化。(看<a href="https://yakovfain.com/2016/07/20/angular-2-guarding-routes/" terget="_blank">这里</a>)
路由可以使用ActivatedRoute的快照属性或通过订阅其属性参数来接收参数。现在有一个属性paramMap,可以通过使用get()方法获取一个特定的参数,或者通过调用getAll()获取所有的参数。
以下是接收上一个路由中没有更改的参数ID的方法:
export class ProductDetailComponentParam { productID: string; constructor(route: ActivatedRoute) { this.productID = route.snapshot.paramMap.get('id'); } }
如果路由在上一个路由中已经更改了,(看<a href="https://yakovfain.com/2016/11/20/angular-2-implementing-master-detail-using-router/" target="_blank">这里</a>)你可以像下面这样订阅id的流:
export class ProductDetailComponentParam { productID: string; constructor(route: ActivatedRoute) { route.paramMap.subscribe( params => this.productID = params.get('id') ); } }
CanDeactivate守卫现在允许您更具体,有条件地禁止从路由导航,具体取决于用户计划导航的位置。接口CanDeactivate现在有一个可选参数nextState,您可以检查以决定是否要禁止导航。下一个代码片段只显示用户尝试导航到由路径“/”表示的归属路由时,显示警告弹出窗口。导航到任何其他路线仍然没有保护。
@Injectable() export class UnsavedChangesGuard implements CanDeactivate<ProductDetailComponent>{ constructor(private _router:Router){} canDeactivate(component: ProductDetailComponent, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot){ let canLeave: boolean = true; // If the user wants to go to home component if (nextState.url === '/') { canLeave = window.confirm("You have unsaved changes. Still want to go home?"); } return canLeave; } }
相关文章推荐
- Angular系列文章之angular路由
- angular ,require.js, angular-async-loader实现单页面路由,控制器js文件分离
- angular4路由基础运用
- angular.js 路由及页面传参
- 详解angular笔记路由之angular-router
- AngularJs route ng路由 单页面应用(下)
- Angular 4.x 路由快速入门学习
- 从Angular2路由引发的前后端路由浅谈
- 关于angular2路由激活状态时class设置
- angular 路由传参
- angular4基础之路由
- Angular最新教程-第八节 路由一(路由配置)
- 【Angular】路由跳转问题;
- Angular中嵌套路由ui-router
- Angular路由实现单页面切换
- [置顶] 在vue路由变化的时候,改变页面的title
- angular路由模拟微信页面切换和页面之间的传值
- angular2/angular4 如何通过$http的post方法请求下载二进制的Excel文件
- Angular 2 路由
- AngularJs ui-router 路由的简单介绍