我有一个像这样实施的守卫:
@Injectable()
export class CustomerGuard implements CanActivate {
constructor(
private authService: AuthenticationService,
private dialog: MatDialog
) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (this.authService.isCustomer) {
return true;
}
const dialog = this.dialog.open(SigninModalComponent, {
data: {
errorMessage: this.authService.isLoggedIn ?
'You don\t have access to this page, please use an appropriate account' :
'Please authenticate to access this page'
}
});
return dialog.afterClosed().pipe(
map(() => {
return this.authService.isCustomer;
})
);
}
}
当我在浏览器的地址栏中键入未经授权的路由时,服务器端呈现显示惰性模式,然后当客户端接管时,会显示另一个工作模式,我可以成功验证并访问所请求的路由。
问题是服务器端渲染的模态永远不会消失......
是否有一个干净的解决方案,这并不意味着不显示服务器端的模式?
我会用DI帮你解决这个问题。我利用他们网站上的Angular Universal样本创建了一个例子。
首先创建一个令牌:app/tokens.ts
import { InjectionToken } from '@angular/core';
export let RENDERED_BY_TOKEN = new InjectionToken('renderedBy');
更新app.module.ts
以使用此标记通过DI容器提供值:
import { RENDERED_BY_TOKEN } from './tokens';
@NgModule({
.
.
.
providers: [
.,
.,
{ provide: RENDERED_BY_TOKEN, useValue: 'client' }
],
.
.
.
export class AppModule { }
更新app.server.module.ts
以使用此标记通过DI容器提供值:
import { RENDERED_BY_TOKEN } from './tokens';
@NgModule({
.
.
.
providers: [
.,
.,
{ provide: RENDERED_BY_TOKEN, useValue: 'server' }
],
.
.
.
export class AppServerModule { }
然后你的代码中的其他地方(我使用了一个组件,但你会把它放在你的路由保护中),使用该标记注入值:
app.component.ts
import { Component, Inject } from '@angular/core';
import { RENDERED_BY_TOKEN } from './tokens';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Tour of Heroes';
renderedBy;
constructor(@Inject(RENDERED_BY_TOKEN) val: string) {
this.renderedBy = val;
}
}
app.component.html
<h1>{{title}}</h1>
<h5>{{renderedBy}}</h5>
<nav>
<a routerLink="/dashboard">Dashboard</a>
<a routerLink="/heroes">Heroes</a>
</nav>
<router-outlet></router-outlet>
<app-messages></app-messages>
如果你运行它,你会看到h5
元素从'server'更新为'client',表明它的工作正常。您可以在if语句中使用此值,以便不显示服务器上的对话框。
UPDATE
通过这篇文章,我注意到了一种更简单的方法。似乎Angular本身为您提供了这些信息,而无需自定义令牌。
在Guard中,您可以使用以下内容进行更新:
import { PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
constructor(@Inject(PLATFORM_ID) private platformId: Object) {
const isServer = !isPlatformBrowser(platformId);
}
UPDATE2
鉴于对这个问题的澄清,我能够实现这一目标的唯一方法似乎不太理想,但到目前为止,我发现这是唯一可行的方法。
document.querySelectorAll('.cdk-overlay-container').forEach(dialog => dialog.remove());
作为参考,我对这个答案的所有工作都是在GitHub repo。