问题描述: 在使用Angular Universal时,当在AuthGuard中使用异步代码时,会出现挂起问题。
解决方法: 在AuthGuard中使用异步代码时,可能会导致服务器端的请求挂起,从而导致应用无法正常渲染。以下是解决这个问题的一种方法:
import { CanActivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { take } from 'rxjs/operators';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(): Observable {
return this.authService.isAuthenticated().pipe(
take(1)
);
}
}
import { NgModule } from '@angular/core';
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
@NgModule({
imports: [
AppModule,
ServerModule,
ServerTransferStateModule,
],
bootstrap: [AppComponent],
})
export class AppServerModule {}
通过实施上述解决方法,可以解决Angular Universal中AuthGuard挂起问题。