Sum*_*wal 1 angular2-routing angular
我有URL http://www.localhost:4200/profile和http://www.localhost:4200/editProfile.这两个URL都提供给登录用户.现在我只想/editProfile通过可用的导航菜单访问,而不是直接在地址栏上写入URL并按Enter键.如果用户这样做,他将被重定向到/profile路径.
类似于允许POST /editProfile但没有GET的东西.
可以使用路由模块中提供的CanActivate来实现吗?
谢谢
萨米特.我问你的目的是因为我解决这个问题的方法不是阻止用户通过地址栏导航.这样做会破坏应该拥有该页面合法访问权限的用户.如果用户已经登录,为什么不允许她直接访问edit profile页面?当用户试图在她的浏览器中使用前进和后退导航按钮时,它也会破坏事物,并且会让我觉得非常令人沮丧.
如果你还想这样做......
您可以CanActivate在路线定义中使用
path: 'editProfile',
component: EditProfileComponent,
canActivate:[EditProfileGuard]
Run Code Online (Sandbox Code Playgroud)
EditProfileGuard 是一种只有在标志设置为true时才允许导航的服务
@Injectable()
export class EditProfileGuard implements CanActivate {
//must be set to true for navigation to succeed
allow = false;
canActivate(){
if(this.allow){
this.allow = false;
return true;
}
else return false;
}
}
Run Code Online (Sandbox Code Playgroud)
如果用户通过浏览器地址栏导航,则她将被拒绝访问,因为它allow是错误的.
当用户单击导航菜单中的链接时,allow在将其发送到新路由之前设置为true
import {EditProfileGuard} from '...'
import {Router} from '@angular/router';
...
export class MyComponent{
constructor(private guard:EditProfileGuard, private router:Router){}
//execute this when link is clicked
goToProfile(){
//so navigation will be allowed
this.guard.allow = true;
this.router.navigateByUrl('editProfile');
}
}
Run Code Online (Sandbox Code Playgroud)
请记住将服务添加到providers您的阵列中AppModule.
回应您的评论如下:
我会checkoutID在摘要页面上创建一个必需的参数,因此路由定义将是/summary/:id结帐页面的链接(或用户保存的URL)id,并且摘要组件可以使用它id来检索和显示详细信息.
如果未签出的用户尝试直接导航到摘要页面,id则会丢失,导航将失败.
在ngOnInit摘要组件中,我将验证id,以便如果用户发明假冒id并尝试导航,我可以重定向而不是加载组件.
这将允许合法用户直接导航,并使前进/后退导航工作.
| 归档时间: |
|
| 查看次数: |
2121 次 |
| 最近记录: |