【Angular】Angular4路由的改变

原文地址: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的方法:

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;
 
    }
}

转载于:https://my.oschina.net/zhongzhong5/blog/1523310

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值