«ApolloError: Ошибка сети» в приложении SSR Angular Universal, apollo-angular - PullRequest
0 голосов
/ 20 октября 2019

Каждый раз, когда я получаю данные в компоненте с помощью apollo-angular во встроенном приложении, появляется всплывающая ошибка и происходит ее сбой. Я действительно не знаю, что означает эта ошибка. Когда я пытался получить больше информации об этом, но больше ничего не показывалось.

ERROR ApolloError: Network error: 
    at new ApolloError (/Users/preq/Documents/Projekty/SR-WEAR/strona/sr-ssr/dist/server/main.js:110628:26)
    at /Users/preq/Documents/Projekty/SR-WEAR/strona/sr-ssr/dist/server/main.js:112117:34
    at /Users/preq/Documents/Projekty/SR-WEAR/strona/sr-ssr/dist/server/main.js:112537:15
    at Set.forEach (<anonymous>)
    at /Users/preq/Documents/Projekty/SR-WEAR/strona/sr-ssr/dist/server/main.js:112535:26
    at Map.forEach (<anonymous>)
    at QueryManager.broadcastQueries (/Users/preq/Documents/Projekty/SR-WEAR/strona/sr-ssr/dist/server/main.js:112533:20)
    at /Users/preq/Documents/Projekty/SR-WEAR/strona/sr-ssr/dist/server/main.js:112012:29
    at ZoneDelegate.invoke (/Users/preq/Documents/Projekty/SR-WEAR/strona/sr-ssr/node_modules/zone.js/dist/zone-node.js:391:26)
    at Object.onInvoke (/Users/preq/Documents/Projekty/SR-WEAR/strona/sr-ssr/dist/server/main.js:42298:33)
    at ZoneDelegate.invoke (/Users/preq/Documents/Projekty/SR-WEAR/strona/sr-ssr/node_modules/zone.js/dist/zone-node.js:390:52)
    at Zone.run (/Users/preq/Documents/Projekty/SR-WEAR/strona/sr-ssr/node_modules/zone.js/dist/zone-node.js:150:43)
    at /Users/preq/Documents/Projekty/SR-WEAR/strona/sr-ssr/node_modules/zone.js/dist/zone-node.js:910:34
    at ZoneDelegate.invokeTask (/Users/preq/Documents/Projekty/SR-WEAR/strona/sr-ssr/node_modules/zone.js/dist/zone-node.js:423:31)
    at Object.onInvokeTask (/Users/preq/Documents/Projekty/SR-WEAR/strona/sr-ssr/dist/server/main.js:42279:33)
    at ZoneDelegate.invokeTask (/Users/preq/Documents/Projekty/SR-WEAR/strona/sr-ssr/node_modules/zone.js/dist/zone-node.js:422:60) {
  graphQLErrors: [],
  networkError: [NetworkError],
  message: 'Network error: ',
  extraInfo: undefined
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sr-ssr@8.0.0 serve:ssr: `node dist/server`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the sr-ssr@8.0.0 serve:ssr script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/preq/.npm/_logs/2019-10-19T20_42_14_051Z-debug.log

App.module:

import {
  BrowserModule,
  BrowserTransferStateModule,
  TransferState,
  makeStateKey
} from '@angular/platform-browser';
import { isPlatformBrowser } from '@angular/common';

import { NgModule, PLATFORM_ID, Inject } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { ApolloModule, Apollo } from 'apollo-angular';
import { HttpLinkModule, HttpLink, HttpLinkHandler } from 'apollo-angular-link-http';
import { InMemoryCache, NormalizedCacheObject } from 'apollo-cache-inmemory';

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'sr-ssr' }),
    AppRoutingModule,
    HttpClientModule,
    ApolloModule,
    HttpLinkModule,
    BrowserTransferStateModule
  ],
  providers: [CookieService],
  bootstrap: [AppComponent]
})
export class AppModule {
  cache: InMemoryCache;
  link: HttpLinkHandler;

  constructor(
    private readonly apollo: Apollo,
    private readonly transferState: TransferState,
    private readonly httpLink: HttpLink,
    @Inject(PLATFORM_ID) readonly platformId: Object
  ) {
    const isBrowser = isPlatformBrowser(platformId);

    this.cache = new InMemoryCache();
    this.link = this.httpLink.create({ uri: '/api' });

    this.apollo.create({
      link: this.link,
      cache: this.cache,
      ...(isBrowser
        ? {
            // queries with `forceFetch` enabled will be delayed
            ssrForceFetchDelay: 200,
          }
        : {
            // avoid to run twice queries with `forceFetch` enabled
            ssrMode: true,
          }),
    });

    if (isBrowser) {
      this.onBrowser();
    } else {
      this.onServer();
    }
  }

  onServer() {
    // serializes the cache and puts it under a key
    this.transferState.onSerialize(STATE_KEY, () => this.cache.extract());
  }

  onBrowser() {
    // reads the serialized cache
    const state = this.transferState.get<NormalizedCacheObject>(
      STATE_KEY,
      null,
    );
    // and puts it in the Apollo
    this.cache.restore(state);
  }
}

Приложение.server.module

import { NgModule } from '@angular/core';
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';

import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';

@NgModule({
  imports: [
    AppModule,
    ServerModule,
    ServerTransferStateModule,
    ModuleMapLoaderModule
  ],
  bootstrap: [AppComponent]
})
export class AppServerModule {}

Ленивый загруженный Component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Apollo } from 'apollo-angular';
import { Subscription } from 'rxjs';

import { getGeneralQuery } from '../../../../src/graphql/getGeneral.query';
import { General } from '../../shared/models/general.interface';

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.scss']
})
export class HomepageComponent implements OnInit, OnDestroy {

  general: General;
  generalSubscription: Subscription;

  constructor(private apollo: Apollo) {
    this.general = new General();
    this.generalSubscription = new Subscription();
  }

  ngOnInit() {
    this.generalSubscription = this.apollo.watchQuery<General>({
      query: getGeneralQuery
    }).valueChanges
    .subscribe(({ data }) => {
      this.general = data.general;
    });
  }

  ngOnDestroy() {
    this.generalSubscription.unsubscribe();
  }
}

Файл схемы запроса

import gql from 'graphql-tag';

    export const getGeneralQuery = gql`
        query GetGeneral {
            general {
              currency
              freeship
              invoicenumber
              invoiceyear
              shopid
            }
         }
      `;

Все в API, протестировано в GraphiQL, работает хорошо.

...