【发布时间】:2018-03-09 12:10:43
【问题描述】:
如果你们碰巧是 facebook 用户,您可能会注意到在用户登录或退出时,Url“https://www.facebook.com”不会改变。我在我正在构建的应用程序中遇到了同样的问题(使用角度 5)。尽管有一些建议的解决方案:
- 首先是使用相同的路由,一个组件(比如:home),在 home 的模板中,我们使用 *ngIf 插入 in、out(组件),在运行时我们检查用户是否登录或退出,基于此,我们显示相应的(输入或输出)组件。
home.component.html
<app-in *ngIf="loggedIn"></app-in>
<app-out *ngIf="!loggedIn"></app-out>
- 我认为会更简洁的第二种方法,尤其是在使用 延迟加载 时,是连续有两条具有相同空路径的路由,并使用 matcher,现在老实说这仍然很难看,因为 matcher 不适合这种高级用途(它也是同步的,并且不包含在服务中 - 例如 canLoad、canActivate..etc- 可以很容易地注入一些其他服务(例如:authService)来检查一个人是否登录或退出)。
home.routing.ts
.
.
.
const routes: Routes = [
{
matcher: matcherFunc,
loadChildren: './in/in.module#InModule'
},
{
path: '',
loadChildren: './out/out.module#OutModule'
}
];
.
.
.
这是匹配函数:
export function matcherFunc(url: UrlSegment[]) {
let currentUser;
currentUser = localStorage.getItem('user');
if (url.length === 0 && currentUser) {
return ({ consumed: url });
} else {
return null;
}
}
当我将我的应用升级为通用时,问题变得更加严重,因为在那种情况下,我不得不在服务器端处理全局变量(window、localStorage..etc) 我被完全困住了!
我相信这个问题已经存在了一段时间了,没有令人满意的答案,有什么建议吗?
【问题讨论】:
标签: angular angular5 server-side-rendering angular-universal