Angular 通用 - 仅适用于爬虫机器人

Angular Universal - Only for crawler bots

我在我的应用程序中使用 Angular Universal,但是当页面加载时我有一些奇怪的闪烁(服务器版本和实际应用程序之间的转换。它不适用于我的路由守卫(前用户帐户页面)。

我只需要用于 SEO 的 SSR...那么也许有一种方法可以仅将 SSR 用于爬虫机器人?并为用户提供经典的 Angular 应用程序?

目前,我正在使用 Angular 通用存储库中的相同 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 解决方案,请查看此问题的答案。