我在我的应用程序中使用了 Angular Universal,但是当页面加载时我有一些奇怪的闪烁(服务器版本和实际应用程序之间的转换。它不能很好地与我有 Guards 的路由(用户帐户页面例如)。
我只需要用于 SEO 的 SSR...那么也许有一种方法可以只将 SSR 用于爬虫机器人?并为用户提供经典的 Angular 应用程序?
目前,我使用的是来自 Angular Universal 存储库的相同 server.ts。
谢谢!
最佳答案
我会告诉你什么,你需要在你的应用程序中使用 Transfer State
。
在这里https://github.com/wizardnet972/universal-seed看到这个 repo,那里正在使用传输状态,
您需要复制应用中的shared/tranfer-state
文件夹,对以下文件进行更改:
app.browser.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { AppModule } from './app.module';
import { BrowserTransferStateModule } from '../shared/transfer-state/browser-transfer-state.module';
@NgModule({
bootstrap: [AppComponent],
imports: [
BrowserModule.withServerTransition({
appId: 'universal-seed'
}),
BrowserTransferStateModule,
AppModule
]
})
export class BrowserAppModule { }
app.server.module.ts
import { NgModule, APP_BOOTSTRAP_LISTENER, ApplicationRef } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { ServerTransferStateModule } from '../shared/transfer-state/server-transfer-state.module';
import { AppComponent } from './app.component';
import { AppModule } from './app.module';
import { TransferState } from '../shared/transfer-state/transfer-state';
import { BrowserModule } from '@angular/platform-browser';
export function onBootstrap(appRef: ApplicationRef, transferState: TransferState) {
return () => {
appRef.isStable
.filter(stable => stable)
.first()
.subscribe(() => {
transferState.inject();
});
};
}
@NgModule({
bootstrap: [AppComponent],
imports: [
BrowserModule.withServerTransition({
appId: 'universal-seed'
}),
ServerModule,
ServerTransferStateModule,
AppModule
],
providers: [
{
provide: APP_BOOTSTRAP_LISTENER,
useFactory: onBootstrap,
multi: true,
deps: [
ApplicationRef,
TransferState
]
}
]
})
export class ServerAppModule {
}
有关传输状态的更多信息,也请查看 https://github.com/AngularClass/angular-universal-transfer-state
如果您正在使用 angular4,上述解决方案将有效,但如果您正在寻找 angular5 解决方案,请查看此问题的答案。
angular universal app performance, APP_BOOTSTRAP_LISTENER, flicker
关于Angular Universal - 仅适用于爬虫机器人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48671609/