簡體   English   中英

Angular Universal TransferState未在客戶端上加載

[英]Angular Universal TransferState not loading on Client

我正在嘗試使用我的Angular Universal v5應用程序中的TransferState 經過大量調試后,我意識到,在服務器上, TransferState似乎正在工作,因為響應包含一個<script id=APP_ID></script>標記,其中包含相應的序列化狀態( TransferState )。

出於某種原因,瀏覽器應用程序尚未使用狀態進行初始化。 如果我將測試狀態硬編碼到我的應用程序的index.html文件中(通過復制和粘貼),那么我的瀏覽器應用程序成功初始化為瀏覽器狀態。 我不確定出了什么問題。 任何想法非常感謝!

我唯一的猜測是,當我在Chrome的檢查器中觀看我的應用程序加載時,看起來好像大部分元素一次被加載,然后在另一個滴答中顯示<script id=APP_ID></script> 這似乎暗示腳本標簽是以某種方式在瀏覽器端生成/處理的,即使我已經檢查了服務器的響應並且它包含腳本標記。 但是,如果腳本標記在客戶端進行某種處理,則可能在處理完成之前初始化TransferState ,這就是我的應用程序未接收狀態的原因。 再次,任何想法都非常感謝!

這是相關代碼:

app.module.ts

import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserModule, BrowserTransferStateModule } from '@angular/platform-browser';
import { environment } from '../environments/environment';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';    
import { AppRoutingModule } from './app-routing.module';
import { GraphQLModule } from './graphql.module';

@NgModule({
  imports: [
    BrowserModule.withServerTransition({ appId: 'service-work-coordination' }),
    BrowserTransferStateModule,
    AppRoutingModule,
    GraphQLModule,
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
})
export class AppModule {}

app.server.module.ts

import { NgModule } from '@angular/core';
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';
import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';

import { AppModule } from './app.module';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    AppModule,
    ServerModule,
    ServerTransferStateModule,
    ModuleMapLoaderModule, // <-- *Important* to have lazy-loaded routes work
  ],
  // Since the bootstrapped component is not inherited from your
  // imported AppModule, it needs to be repeated here.
  bootstrap: [AppComponent],
})
export class AppServerModule {}

graphql.module.ts

import { NgModule, APP_ID, PLATFORM_ID, Inject } from '@angular/core';
import { TransferState, makeStateKey } from '@angular/platform-browser';
import { HttpClientModule, HttpHeaders } from '@angular/common/http';
import { environment } from '../environments/environment';

// Apollo
import { ApolloModule, Apollo } from 'apollo-angular';
import { HttpLinkModule, HttpLink, HttpLinkHandler } from 'apollo-angular-link-http';
import { InMemoryCache, NormalizedCache, NormalizedCacheObject } from 'apollo-cache-inmemory';
import { setContext } from 'apollo-link-context';
import { isPlatformBrowser } from '@angular/common';

const uri = environment.uris.api.graphql;

const STATE_KEY = makeStateKey<any>('apollo.state');

@NgModule({
  imports: [
    HttpClientModule,
    ApolloModule,
    HttpLinkModule,
  ],
  exports: [
    HttpClientModule,
    ApolloModule,
    HttpLinkModule,
  ]
})
export class GraphQLModule {
  private cache: InMemoryCache;
  private link: HttpLinkHandler;

  constructor(
    private apollo: Apollo,
    private transferState: TransferState,
    private httpLink: HttpLink,
    @Inject(PLATFORM_ID) private platformId: any,
  ) {
    this.cache = new InMemoryCache();
    this.link = this.httpLink.create({ uri });

    console.log('transferState: ', this.transferState);

    const isBrowser = this.transferState.hasKey<NormalizedCache>(STATE_KEY);

    if (isPlatformBrowser(this.platformId)) {
      this.apollo.create({
        link: this.link,
        cache: this.cache,
        ssrForceFetchDelay: 100,
      });

      this.onBrowser();      
    } else {      
      this.apollo.create({
        link: this.link,
        cache: this.cache,
        ssrMode: true,
      });

      this.onServer();      
    }
  }

  onServer(): void {
    this.transferState.onSerialize(STATE_KEY, () => this.cache.extract());
  }

  onBrowser(): void {
    const state = this.transferState.get<NormalizedCacheObject | null>(STATE_KEY, null);

    if (state) {
      this.cache.restore(state);      
    }
  }
}

簡化的服務器響應

<html>
<head>...app code...</head>
<body>
<app-root>...app code...</app-root>
<script type="text/javascript" src="inline.6ce41075b82d3dba433b.bundle.js"></script>
<script type="text/javascript" src="polyfills.37cc021a2888e752595b.bundle.js"></script>
<script type="text/javascript" src="main.1efdc21cec25daa396d1.bundle.js"></script>
<script id="service-work-coordination-state" type="application/json">{&q;apollo.state&q;:{&q;$ROOT_QUERY.person({\&q;id\&q;:\&q;074a9421-53bb-44c7-8afe-43130c723bd9\&q;})&q;:{&q;firstName&q;:&q;John&q;,&q;middleName&q;:null,&q;lastName&q;:&q;Carroll&q;,&q;primaryEmailAddress&q;:&q;:`EmailAddress::Person::Current`:`EmailAddress::Person`:`EmailAddress::Current`:`EmailAddress`:`Current` {uuid: &s;f0c4896a-27da-410b-84d3-3d66e1507a7e&s;}&q;,&q;__typename&q;:&q;Person&q;},&q;ROOT_QUERY&q;:{&q;person({\&q;id\&q;:\&q;074a9421-53bb-44c7-8afe-43130c723bd9\&q;})&q;:{&q;type&q;:&q;id&q;,&q;id&q;:&q;$ROOT_QUERY.person({\&q;id\&q;:\&q;074a9421-53bb-44c7-8afe-43130c723bd9\&q;})&q;,&q;generated&q;:true}}}}</script>
</body>
</html>

Uggg ......事實證明,我已經遇到了Angular中一個已知(謝天謝地)的錯誤 TransferState在腳本標簽被處理/加載以某種方式啟動客戶端上。 為了解決這個問題,目前您需要延遲角度客戶端應用程序的引導。

更新main.ts

document.addEventListener('DOMContentLoaded', () => {
  platformBrowserDynamic()
  .bootstrapModule(AppModule)
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM