gpt4 book ai didi

Angular 5 路由回退

转载 作者:行者123 更新时间:2023-12-03 19:35:59 26 4
gpt4 key购买 nike

在我的应用程序路由模块中,我想将用户重定向到仪表板(如果已登录)或主页(如果未登录)。

我正在使用 guard 进行此检查。

来自 应用路由.module.ts

 class LoggedInUser implements CanActivate {
constructor(@Inject(LoginService) private loginService: LoginService) {}

canActivate() {
return new Promise<boolean>((resolve, reject) => {
this.loginService.isAuthenticated({
isLoggedIn(message: string, loggedIn: boolean) {
resolve(loggedIn);
}
});
});
}
}

const routes: Routes = [
{ path: '', loadChildren: 'app/dashboard/dashboard.module#DashboardModule', canActivate: [LoggedInUser] },
{ path: '**', loadChildren: 'app/homepage/homepage.module#HomepageModule' }
];

这允许我在登录时访问仪表板,这是我想要的,但它是 不是 否则将我重定向到主页。

如何启用此回退?我已经搜索了几个小时,我所能找到的只是一些以编程方式调用路由器的代码示例,以到达像“/login”这样的专用路径,但我不想要这样的路径。

最佳答案

您可以使用路由器手动将它们导航到登录页面,这是我想到的一个粗略的想法:

 class LoggedInUser implements CanActivate {
constructor(@Inject(LoginService) private loginService: LoginService, private router: Router) {}

canActivate() {
return new Promise<boolean>((resolve, reject) => {
this.loginService.isAuthenticated({
isLoggedIn(message: string, loggedIn: boolean) {
resolve(loggedIn);
}
});
}).then(loggedIn => {
if(!loggedIn) {
this.router.navigate['login'];
}
return loggedIn;
});
}

更新:7+(使用 urlTree)

引自 here

Now, for CanActivate, CanActivateChild, and CanDeactivate, there is a third option; these guards can return a UrlTree directly. In these scenarios, the current navigation is cancelled, and a new navigation is created, which routes to the path specified by the returned UrlTree. For example, if a user fails an authentication guard, you may want to redirect that user directly to the login page.



代码取自 here
import { Injectable } from '@angular/core';
import { CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot,
Router,
UrlTree } from '@angular/router';

@Injectable()
export class CanActivateRouteGuard implements CanActivate {

constructor(private router: Router) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree {
const url = 'target';
const tree: UrlTree = this.router.parseUrl(url);
return tree;
}
}

关于Angular 5 路由回退,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48747528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com